在下面的代码中,我试图理解init新和. 我遇到的问题是方法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 workspaceVarargs.py", line 15, in <module>
v = varargs()
File "d:python workspaceVarargs.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()