Runtime Error: RecursionError: maximum recursion depth exceeded while calling a Python object

Runtime Error: RecursionError: maximum recursion depth exceeded while calling a Python object

我有许多派生的 class 的 foo class,我正在尝试将基础 class 的对象实例化为派生的 class 之一。我只想调用 base class 的构造函数一次。 我在尝试执行以下代码时出现运行时错误:

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

发生这种情况是因为 call_once 是一个 class 变量,但您将 False 分配给 call_once 实例变量。要修复它,检查并将 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