装饰器
s1.pydef outer(func): def inner(): print("before") func() print("after") return inner @outer def f1(): print("F1") s2.pyimport s1s1.f1()
#输出
before
F1
after
装饰器格式
@+函数
功能
1 自动执行outer函数并且将下面的函数名f1当作参数传递
2 将outer函数的返回值,重新赋值给f1
f1重新赋值成装饰器函数的内存函数
f1等于inner这个函数
装饰器之返回值
def outer(func): def inner(): print("before") r = func() print("after") return r return inner @outer def f1(): print("F1") return "dada" import zsq ret = zsq.f1() print(‘fanhuizhi‘,ret)
#输出
before
F1
after
fanhuizhi dada
装饰器之参数
def outer(func): def inner(a): print("before") r = func(a) print("after") return r return inner @outer def f1(arg): print(arg) return "dada" import zsq ret = zsq.f1(‘aaa‘) print(‘fanhuizhi‘,ret)
#输出
before
aaa
after
fanhuizhi dada
def outer(func): def inner(*args,**kwargs): print("before") r = func(*args,**kwargs) print("after") return r return inner @outer def f1(arg): print(arg) return "dada" @outer def f2(a1,a2): print(a1) print(a2) import zsq ret = zsq.f1(‘aaa‘) print(‘fanhuizhi‘,ret) zsq.f2(11,22)
#输出
before
aaa
after
fanhuizhi dada
before
11
22
after
时间: 2024-10-14 22:29:49