装饰器
- decorator的本质他就是函数
- 原则:--对于被装饰的函数他不发生任何变化,他是透明的。
- 不能修改被装饰的函数的源代码
- 不能修改被装饰的函数的调用方式
- 函数就是"变量":
- 普通变量。先定义后使用:如x=1,先定义变量x和再调用变量;函数也如此,先定义函数在调用函数;
python
#第一步:定义
def fibo(x):
if x==0:
return 1
elif x==1:
return 1
else:
return fibo(x-1) + fibo(x-2)
#第二步:调用
print(fibo(10))
- 存储也是一样,函数名以及函数体存储:普通变量x为名牌号,1为值存储在内存中,函数则函数名为名牌号,函数体存储在内存中

- 匿名函数:特殊的匿名函数没有函数名,用完即回收:
lambda x :print(x)
- 高阶函数;如
def test(x,y,func)- 把一个函数当做参数传参给另外一个函数
- 返回值包含函数名
python
def sum(a,b,c):
return a+b+c
#sum是函数名,为传参
def fun(a,b,c,sum):
print("count:")
return sum(a,b,c) #返回值sum函数名
print(fun(1, 2, 3, sum))
- 函数嵌套:定义函数时函数中包含另外一个函数。
python
def foo():
print('in the foo')
def bar(): #函数foo中的函数
print('in the bar')
bar()
foo()
- 装饰器=高阶函数+嵌套函数
python
def decorator(func): #func_test01传值给func 高阶函数
def wrapper(*args,**kwargs): #嵌套函数 参数组
start_time = time.time()
func(*args,**kwargs) #调用func_test01 参数组
stop_time = time.time()
print("the fun runtime is {}".format(stop_time - start_time))
return wrapper #返回这个函数的内存地址
@decorator #func_test01=decorator(func_testo1)
def fun_test01(): #原函数的源代码不变
time.sleep(1)
print('in fun_test01')
fun_test01() #函数调用方式不变
- 带参数组的装饰器:三层嵌套
python
import time
user_name="agan"
password="123"
def auth(auth_type):
def outer_wrapper(func):
print("you auth_type is {}".format(auth_type))
def wrapper(*args, **kwargs):
print('wrapper func args:',*args,**kwargs)
if auth_type == 'local':
uname = input("Please input your username: ").strip() #去掉字符串开头和结尾的空白字符
psd = input("Please input your password: ").strip()
if uname == user_name and psd == password:
print("you have authenticated!")
res = func(*args, **kwargs) # 调用func
return res
else:
print("wrong username or password!")
else:
print("wrong auth type!")
return wrapper
return outer_wrapper
def index():
print("welcome to index page")
@auth(auth_type="local") # home = outer_wrapper
def home():
print("welcome to home page")
index()
home()