【发布时间】:2011-04-28 08:33:56
【问题描述】:
我正在尝试使用以下代码装饰一个实际的类:
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:
典型实现通过使用带有适当参数的
super(currentclass, cls).__new__(cls[, ...])调用超类的__new__()方法来创建类的新实例,然后在返回之前根据需要修改新创建的实例。如果
__new__()返回一个cls 的实例,那么新实例的__init__()方法将像__init__(self[, ...])一样被调用,其中self 是新实例,其余参数与传递给__new__()的参数相同。
知道为什么__init__ 没有运行吗?
另外,我曾尝试像这样拨打__new__:
return super(cls.__bases__[0], cls).__new__(cls)
但它会返回一个TypeError:
TypeError: super.__new__(TestClass): TestClass is not a subtype of super
【问题讨论】: