【问题标题】:method is not getting called from within __new__没有从 __new__ 中调用方法
【发布时间】:2021-05-23 05:42:24
【问题描述】:

在下面的代码中,我试图理解 initnew。我遇到的问题是从未调用方法 callBeforeInit()。

请告诉我为什么它没有被调用以及如何调用它。

代码

class varargs:

def __new__(cls):
    print("in object creation")
    callBeforeInit()
    return super(varargs, cls).__new__(cls)
    #return object.__new__(cls)

def __init__(self):
    print("in object indtansiation")

def callBeforeInit():
    print("called before init")

v = varargs()

错误

in object creation
Traceback (most recent call last):
File "d:\python workspace\Varargs.py", line 15, in <module>
v = varargs()
File "d:\python workspace\Varargs.py", line 5, in __new__
callBeforeInit()
NameError: name 'callBeforeInit' is not defined

【问题讨论】:

  • 您的代码不是指一个方法——例如cls.callBeforeInit——它指的是一个词法范围的可调用对象——即只是callBeforeInit。正如错误所说,没有定义这样的东西。

标签: python new-operator init


【解决方案1】:

new在创建对象之前被调用,所以此时不​​存在这样的方法。

应该是

class varargs:

    def __new__(cls):
        print("in object creation")
        cls.callBeforeInit()
        return super(varargs, cls).__new__(cls)
        #return object.__new__(cls)

    def __init__(self):
        print("in object indtansiation")

    @classmethod
    def callBeforeInit(cls):
        print("called before init")

v = varargs()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-31
    • 1970-01-01
    • 2020-10-23
    • 1970-01-01
    • 2010-09-26
    • 1970-01-01
    相关资源
    最近更新 更多