【发布时间】:2021-05-23 05:42:24
【问题描述】:
在下面的代码中,我试图理解 init 和 new。我遇到的问题是从未调用方法 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