今天的課程總結:
- 裝飾器
- 迭代器&生成器
- json&pickle實現數據的序列化
- 軟件目錄結構規范
一、裝飾器
裝飾器的本質是函數,起目的就是用來為其它函數增加附加功能
原則:不能修改被裝飾函數的源代碼;被裝飾函數的調用方式不能改變 ,簡而言之就是轉時其對於函數就是透明的,對被裝飾的函數是沒有影響的。
實現裝飾器的知識儲備:函數即變量;高階函數;嵌套函數;最終高階函數加上嵌套函數就構成了裝飾器,函數也就是一種變量
知識點介紹:
函數即變量
高階函數:
a.把一個函數名仿作實參傳給另外一個函數(不修改裝飾函數源代碼的情況下為其添加功能)
import time
def test1(func):
start_time = time.time()
func()
stop_time = time.time()
print("toyal %s"%(stop_time-start_time))
def bar():
time.sleep(3)
print("in the bar!!")
test1(bar) #其中,test1相當於是一個裝飾器,但不完全是。test1(bar)
b.返回值中包含函數名(不用修改函數的調用方式)
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import time
def test1(func):
print(func)
return func
def bar():
time.sleep(3)
print("in the bar!!")
bar = test1(bar)
bar()
嵌套函數:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#函數的嵌套
def foo():
print("hello World")
def bar():
print('in the bar!!')
bar()
foo()
然后就是裝飾器了:說白了裝飾器就是高階函數和嵌套函數的結合
裝飾器的一個栗子:
import time
##裝飾器部分
def timer(func):
def deco():
start_time = time.time()
#return func()
func()
stop_time = time.time()
print("total is %s:"%(stop_time-start_time))
return deco
@timer #調用裝飾器
##test1和test2函數相當於是源代碼,然而一直沒改變原代碼而是顯得功能添加,這就是裝飾器達成的效果
def test1():
time.sleep(1)
print('test1')
@timer #裝飾器外城函數名
def test2():
time.sleep(2)
print("test2")
test1()
test2()
要是傳入了參數,就利用參數組修改:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import time
def timer(func):
def deco(*args): #如果帶了參數組,下面源代碼中的參數傳遞就可以被調用了
start_time = time.time()
func(*args)
stop_time = time.time()
print("total is %s"%(stop_time-start_time))
return deco
@timer
def test1():
time.sleep(0.1)
print("heheheheh")
@timer
def test2(name):
time.sleep(1)
print("test2",name)
test1()
test2("wanghui")
