【发布时间】:2021-03-25 21:34:27
【问题描述】:
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__ 中返回了类 Decorator 的相同实例。
【问题讨论】:
-
你写了
return self;为什么你会期望它返回一个不同的对象? -
你用
@Decorator装饰了一个类,所以你的代码执行一次Decorator构造函数来创建一个Decorator对象。它不能等同于创建两个Decorator对象的任何代码。 -
它指的是您的代码创建的
Decorator的一个单一实例;Decorator的实例也绑定到名称C。 -
你得到一个
decorator实例,但有两个C实例 -
你可以通过用它装饰更多的东西来创建更多
Decorator类的实例——所以它不是单例,不。C类也不是单身人士;您的__call__方法每次都会创建它的一个新实例。