我尝试使用以下代码装饰一个实际的类:
def my_decorator(cls):
def wrap(*args, **kw):
return object.__new__(cls)
return wrap
@my_decorator
class TestClass(object):
def __init__(self):
print "__init__ should run if object.__new__ correctly returns an instance of cls"
test = TestClass() # shouldn't TestClass.__init__() be run here?
我没有收到错误,但是我也没有看到来自TestClass.__init__()
的消息。在
根据the docs for new-style classes:
Typical implementations create a new instance of the class by invoking the superclass’s
__new__()
method usingsuper(currentclass, cls).__new__(cls[, ...])
with appropriate arguments and then modifying the newly-created instance as necessary before returning it.If
__new__()
returns an instance of cls, then the new instance’s__init__()
method will be invoked like__init__(self[, ...])
, where self is the new instance and the remaining arguments are the same as were passed to__new__()
.
你知道__init__
为什么不运行吗?在
另外,我尝试过这样调用__new__
:
但它会返回一个TypeError
:
TypeError: super.__new__(TestClass): TestClass is not a subtype of super
__init__
没有运行,因为object.__new__
不知道调用它。如果你改成cls.__call__(*args, **kwargs)
,或者更好,cls(*args, **kwargs)
,它应该可以工作。请记住,类是可调用的:调用它会生成一个新实例。仅仅调用__new__
就返回一个实例,但不经过初始化。另一种方法是调用__new__
,然后手动调用__init__
,但这只是替换__call__
中已经包含的逻辑。在您引用的文档是指在类的
__new__
方法中从调用super
。在这里,你是在外面打电话,而不是像我已经讨论过的那样。在无法告诉您原因,但此黑客确实运行
__init__
相关问题 更多 >
编程相关推荐