标签:定义 封装 nbsp turn 参数 原函数 *args 字典 函数名
1 def outer(func): 2 def inner(): 3 print("hello") 4 print("hello") 5 #func为原f的函数 6 r=func() # r=none 7 print("end") 8 print("rend") 9 return r 10 return inner 11 @outer #装饰器的本质将原函数封装到新函数,执行outer函数,并县城将其下面的的函数名做为参数传到到 12 #传到func中,将outer的返回值重新赋值 给f1=outer的返回值 inner就是地 13 #只要应用装饰器,函数就被重新定义,重新定义为inner函数内层的函数 14 def f(): 15 16 print("F1") 17 f()
有参数的
1 def outer(func): 2 def inner(a1,a2): 3 print("hello") 4 print("hello") 5 #func为原f的函数 6 r=func(a1,a2) # r=none 7 print("end") 8 print("end") 9 return r 10 return inner 11 12 13 @outer 14 def f1(a1,a2): 15 return a1+a2 16 f1(1,2)
多个参数(有时传一个,传两个,有时传三个)
1 def outer(func): 2 def inner(*args): 3 print("hello") 4 print("hello") 5 #func为原f的函数 6 r=func(*args) # r=none 7 print(r) 8 print("end") 9 print("end") 10 return r 11 return inner 12 @outer 13 def f1(a1,a2): 14 return a1+a2 15 f1(1,2)
多个参数,有字典
1 def outer(func): 2 def inner(*args,**kargs): 3 print("hello") 4 print("hello") 5 #func为原f的函数 6 r=func(*args,**kargs) # r=none 7 print(r) 8 print("end") 9 print("end") 10 return r 11 return inner 12 @outer 13 def f1(a1,a2): 14 return a1+a2 15 f1(1,2)
多个装饰器加在一个函数
def outer0(func): def inner(*args,**kwargs): print("sbsb") r = func(*args,**kwargs) return r return inner def outer(func): def inner(*args,**kargs): print("hello") print("hello") #func为原f的函数 r=func(*args,**kargs) # r=none print(r) print("end") print("end") return r return inner @outer0 #先执行第一个装饰器 @outer #执行第二个装饰器 def f1(a1,a2): return a1+a2 f1(1,2)
运行结果
sbsb
hello
hello
3
end
end
标签:定义 封装 nbsp turn 参数 原函数 *args 字典 函数名
原文地址:http://www.cnblogs.com/wang43125471/p/7625492.html