Python类D

2024-06-02 13:28:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用以下代码装饰一个实际的类:

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 using super(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__

^{pr2}$

但它会返回一个TypeError

TypeError: super.__new__(TestClass): TestClass is not a subtype of super

Tags: oftheinstanceselfnewreturnobjectinit
2条回答

__init__没有运行,因为object.__new__不知道调用它。如果你改成 cls.__call__(*args, **kwargs),或者更好,cls(*args, **kwargs),它应该可以工作。请记住,类是可调用的:调用它会生成一个新实例。仅仅调用__new__就返回一个实例,但不经过初始化。另一种方法是调用__new__,然后手动调用__init__,但这只是替换__call__中已经包含的逻辑。在

您引用的文档是指在类的__new__方法中从调用super。在这里,你是在外面打电话,而不是像我已经讨论过的那样。在

无法告诉您原因,但此黑客确实运行__init__

def my_decorator(cls):
    print "In my_decorator()"
    def wrap(*args, **kw):
        print "In wrap()"
        return cls.__init__(object.__new__(cls), *args, **kw)
    return wrap

@my_decorator
class TestClass(object):
    def __init__(self):
        print "__init__ should run if object.__new__ correctly returns an instance of cls"

相关问题 更多 >