我在调用其父类的 init 方法时遇到了一个子类的问题,该子类具有多个父类(super class)。我得到一个关于如何未绑定(bind) __init__
需要父实例的错误,但得到了子实例。 StackOverflow 上的其他一些问题指出,这是来自多次定义的父类,我通过在解释器中输入简单的脚本来确认这一点。
注意:这不是我提出问题的代码。举例说明Base类被重新定义导致Inherited类不能正常运行的问题。
>>> class Base(object):
... def __init__(self):
... print "Base!"
...
>>> class Inherited(Base):
... def __init__(self):
... Base.__init__(self)
... print "Inherited"
...
>>> class Base(object):
... def __init__(self):
... print "Base!"
...
>>> Inherited()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in __init__
TypeError: unbound method __init__() must be called with Base instance as first argument (got Inherited instance instead)
>>>
我的问题是,如何防止基类被多次定义?我正在处理的项目有多个文件并到处导入,因此很难重构所有内容以仅包含一次文件。
最佳答案
您在上面确定的问题是因为 Inherited
继承了 Base
的原始定义(您定义的第一个),因为类定义在读取时被处理。
但是,在运行时,Base
的 second 定义的 __init__
被使用。此类需要一个自身的实例,但接收的是 Base
的第一个定义的实例。
当您以这种方式输入内容时,解释器无法知道它们是同一个类。但是当从文件导入时,你不会有这个问题,因为 Python 足够聪明,知道当一个文件被导入两次时,类是相同的。
您的代码发生了一些其他问题,查看更具体的用例会很有帮助。仅当您在多个模块中定义同名类,然后将它们导入同一命名空间时,才会出现此问题。
关于python - 在 Python 中,如何防止类定义被多次包含?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13915421/