1、疊加裝飾器app
定義:在同一個被裝飾對象,添加多個裝飾器,並執行。工具
疊加裝飾器的裝飾順序與執行順序
裝飾順序:由下往上裝飾。
執行順序:由上往下執行。spa
注意:裝飾器在調用被裝飾對象時纔會執行添加功能。code
def wrapper1(func): def inner1(*args,**kwargs): print('1') res = func(*args,**kwargs) print('2') return res return inner1 def wrapper2(func): def inner2(*args,**kwargs): print('3') res = func(*args,**kwargs) print('4') return res return inner2 def wrapper3(func): def inner3(*args,**kwargs): print('5') res = func(*args,**kwargs) print('6') return res return inner3 @wrapper1 #inner1 = wrapper1(inner2) @wrapper2 #inner2 = wrapper2(inner3) @wrapper3 #inner3 = wrapper3(foo) def foo(): print('from foo') foo()
2、有參裝飾器對象
def wrapper(user): def outer(func): #func = foo def inner(*args,**kwargs): if user == 'f': print('welcome haha') #添加用戶的功能 res = func(*args,**kwargs) #func() = foo() return res elif user == 'k': print('sorry neinei') #添加用戶的功能 res = func(*args,**kwargs) #func() = foo() return res return inner return outer @wrapper("k") #outer = wrapper(foo) def foo(): #被裝飾對象 print('from foo') foo()
3、wraps修復工具blog
#不導包的樣子 # def wrapper(func): # def inner(*args,**kwargs): # ''' # 這是裝飾器的註釋 # :param args: # :param kwargs: # :return: # ''' # res = func(*args,**kwargs) # return res # return inner # @wrapper # def foo(): # ''' # 這是被裝飾對象的註釋 # :return: # ''' # print('from foo') # foo() # print(foo) #<function wrapper.<locals>.inner at 0x0000000009E352F0> 此時是裝飾器的註釋 #導包以後 from functools import wraps def wrapper(func): @wraps(func) #修更名稱空間 foo--->func def inner(*args,**kwargs): ''' 這是裝飾器的註釋 :param args: :param kwargs: :return: ''' res = func(*args,**kwargs) return res return inner @wrapper def foo(): ''' 這是被裝飾對象的註釋 :return: ''' print('from foo') # foo() print(foo.__doc__)