未从 __new__ 中调用方法

method is not getting called from within __new__

在下面的代码中,我试图理解 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

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()