繁体   English   中英

为什么 Python 的 __call__ 返回相同的装饰器实例?

[英]Why does the Pythons __call__ return the same Decorator instance?

class Decorator:
def __init__(self, C):
    self.C = C

def __call__(self, *args):
    self.wrapped = self.C(*args)
    return self


@Decorator
class C:
    def __init__(self, attr):
        self.attr = attr

x = C('hello')
y = C('world')
print(x)
print(y)

结果:

<__main__.Decorator object at 0x000000000056A400>
<__main__.Decorator object at 0x000000000056A400>

我不明白为什么在方法__call__中返回了 class 装饰器的相同实例。

装饰器“绑定”到 class,而不是实例。 添加计数器使其更清晰:

class Decorator:
    count = 0

    def __init__(self, C):
        self.C = C

    def __call__(self, *args):
        self.count += 1
        self.wrapped = self.C(*args)
        print('Decorator counter: %d' % self.count)
        return self


@Decorator
class C:
    count = 0

    def __init__(self, attr):
        self.count += 1
        self.attr = attr
        print(self)
        print('C counter: %d' % self.count)


x = C('hello')
y = C('world')
print(x)
print(y)

出去:

<__main__.C object at 0x1070ec050>
C counter: 1 # adds one to each instance
Decorator counter: 1
<__main__.C object at 0x1070ec0d0>
C counter: 1 # adds one to each instance
Decorator counter: 2 # sums up!
<__main__.Decorator object at 0x1070e7fd0>
<__main__.Decorator object at 0x1070e7fd0>

暂无
暂无

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

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