简体   繁体   中英

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)

Result:

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

I cannot understand why the same instance of the class Decorator is returned in the method __call__ .

Decorators are 'binded' to the class, not the instance. Adding a counter makes it clearer:

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)

Out:

<__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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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