我有很多foo类的派生类,我试图将基类的对象实例化为派生类之一。我想只调用一次基类的构造函数。 我在尝试执行以下代码时遇到运行时错误:
class foo():
call_once = True
_Bar = None
_BaseClass = None
def __init__(self):
if (self.call_once):
self.call_once = False
self._Bar = bar()
self._BaseClass = _bar
class bar(foo):
def __init__(self):
foo.__init__(self)
bar1 = bar()
答案 0 :(得分:2)
这是因为call_once是一个类变量,但是您为call_once实例变量赋予了False。要解决此问题,请检查并将False
分配给foo.call_once
。
class foo():
call_once = True
_Bar = None
_BaseClass = None
def __init__(self):
if (foo.call_once):
foo.call_once = False
self._Bar = bar()
self._BaseClass = _bar