Python 具有多个基类的类中继承属性的问题
编辑: 感谢您提供有关类属性的信息。据我所知,它们与其他面向对象语言中的static类似。现在在下面的代码中,我希望使用基类的Python 具有多个基类的类中继承属性的问题,python,multiple-inheritance,Python,Multiple Inheritance,编辑: 感谢您提供有关类属性的信息。据我所知,它们与其他面向对象语言中的static类似。现在在下面的代码中,我希望使用基类的\uuu init\uu在派生类中设置x和y。任何指导都将不胜感激 class Base1: def __init__(self, x): self.x = x class Base2: def __init__(self, y): self.y = y class Derv (Base1, Base2): def __init__
\uuu init\uu
在派生类中设置x
和y
。任何指导都将不胜感激
class Base1:
def __init__(self, x):
self.x = x
class Base2:
def __init__(self, y):
self.y = y
class Derv (Base1, Base2):
def __init__(self, x, y):
self.x = x
self.y = y
旧的:
有关
现在,下面的示例中发生了什么(d字典为空):
尽管当我们将代码更改为以下内容时,这是可行的:
class Base1:
x = 0
def __init__(self, x):
self.x = x
class Base2:
y = 0
def __init__(self, y):
self.y = y
class Derv (Base1, Base2):
def __init__(self, x, y):
self.x = x
self.y = y
我认为这更多是因为在
Derv
的方法中定义了x和y
。但是,如果我希望使用基类构造函数设置值,正确的方法是什么?最简单、最好的方法是:只需调用每个基类中的初始值设定项
class Derv(Base1, Base2):
def __init__(self, x, y):
Base1.__init__(self, x)
Base2.__init__(self, y)
您的两个基类都有一个名称相同的class属性和一个instance属性,这只是自找麻烦。@Martineau。OP没有正确使用父构造函数,这一事实加剧了这种情况。事实上,我一直在寻找调用基类构造函数的正确语法。非常感谢,这就是我一直在寻找的。尝试使用super()。\uuuu init\uuuuu(),但无法获得所需的结果。
class Derv(Base1, Base2):
def __init__(self, x, y):
Base1.__init__(self, x)
Base2.__init__(self, y)