简体   繁体   English

为什么类实例装饰器会跳过代码?

[英]Why does class instance decorator skip code?

Try running the code below.尝试运行下面的代码。 Why does the output only print the "gets skipped" one time?为什么输出只打印一次“被跳过”? We call rotate_list three times and I don't understand why it doesn't run all of the code inside __call__() each time.我们调用了rotate_list 三次,我不明白为什么它每次都不运行__call__()所有代码。 My guess is that it is only printing it once for instantiation or something.我的猜测是它只打印一次用于实例化或其他东西。

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 is called when you define rotate_list , not when you call rotate_list . another ,当你定义叫做rotate_list ,而不是当你调用rotate_list The name rotate_list is rebound to whatever another returns.名称rotate_list被反弹到任何another返回。

@another
def rotate_list(l):
    ...

is equivalent to相当于

def rotate_list(l):
    ...

rotate_list = another(rotate_list)

When python interpreter encounters a function with a decorator it changes the function with the wrapper function.当 python 解释器遇到一个带有装饰器的函数时,它会用包装器函数更改函数。 For your program rotate_list = another(rotate_list) happen in line 14. This calling the __call__ method so it's printing "gets skipped" once.对于你的程序rotate_list = another(rotate_list)发生在第 14 行。这个调用__call__方法所以它打印“被跳过”一次。

Then when you call rotate_list function it is just calling wrap function.然后当你调用rotate_list函数时,它只是调用wrap函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM