由淺入深,走進Python裝飾器-----第三篇:進階--類裝飾函數

**類裝飾器**  
@類
函數


2.1 用類裝飾器來擴展原函數

# 用類裝飾器來擴展原函數,  通過對象函數化觸發__call__方法,進行返回
class KuoZhan():
    def __call__(self,f):
        return self.newfunc(f)
    def newfunc(self,f):
        def in_newfunc():
            print("1")
            f()
            print("2")
        return in_newfunc

@KuoZhan()        #1.  KuoZhan() ==> obj    2. @obj  ==>  obj( )   3.  func = obj( func)                                                                       
def func():
    print("我是原函數")

func()

>>>1
>>>我是原函數
>>>2

2.2 用類裝飾器來擴展原函數

# 直接調用類函數
class KuoZhan():
    def newfunc(f):
        def in_newfunc():
            print("1")
            f()
            print("2")
        return in_newfunc

@KuoZhan.newfunc     # 直接類調用 1. @KuoZhan.newfunc2  ==> KuoZhan.newfunc2()    2. func = KuoZhan.newfunc2(func) = in_newfunc(func)  
def func():
    print("我是原函數")

func()

>>>1
>>>我是原函數
>>>2

2.3 類裝飾類裏的函數

待續....
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章