簡體   English   中英

為什么類實例裝飾器會跳過代碼?

[英]Why does class instance decorator skip code?

嘗試運行下面的代碼。 為什么輸出只打印一次“被跳過”? 我們調用了rotate_list 三次,我不明白為什么它每次都不運行__call__()所有代碼。 我的猜測是它只打印一次用於實例化或其他東西。

class anothercall:
    def __init__(self):
        self.enabled = True
    def __call__(self,f):
        print("gets skipped")
        
        def wrap(*args, **kwargs):
            if self.enabled:
                print('calling {}'.format(f))
            return f(*args, **kwargs)
        return wrap

another = anothercall()
@another
def rotate_list(l):
    return l[1:] + [l[0]]
    
l = [1,2,3]
rotate_list(l)
l = [1,2,3]
rotate_list(l)
l = [1,2,3]
rotate_list(l)

another ,當你定義叫做rotate_list ,而不是當你調用rotate_list 名稱rotate_list被反彈到任何another返回。

@another
def rotate_list(l):
    ...

相當於

def rotate_list(l):
    ...

rotate_list = another(rotate_list)

當 python 解釋器遇到一個帶有裝飾器的函數時,它會用包裝器函數更改函數。 對於你的程序rotate_list = another(rotate_list)發生在第 14 行。這個調用__call__方法所以它打印“被跳過”一次。

然后當你調用rotate_list函數時,它只是調用wrap函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM