[英]Issue with inherited attributes in a class with multiple base classes
EDIT: Thanks for the information about the class attributes.编辑:感谢有关类属性的信息。 I understand these are similar to static in other OO languages.
我知道这些类似于其他 OO 语言中的静态。 Now in the following code, I wish to use the
__init__
of the base classes to set x
and y
in the derived class.现在在下面的代码中,我希望使用基类的
__init__
来设置派生类中的x
和y
。 Any guidance would be appreciated.任何指导将不胜感激。
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
OLD:老的:
Related to Multiple inheritance: The derived class gets attributes from one base class only?与多重继承相关:派生类仅从一个基类获取属性?
Now, what is happening in the following example (dictionary of d is empty):现在,在以下示例中发生了什么(d 的字典为空):
class Base1:
x = 10
class Base2:
y = 10
class Derv (Base1, Base2):
pass
d=Derv()
print (d.__dict__)
Although this works when we change the code to following:虽然这在我们将代码更改为以下时有效:
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
I think this is more because of defining x and y
in the __init__
method of Derv
.我认为这更多是因为在
Derv
的__init__
方法中定义了x and y
。 But, if I wish to set the values using base class constructors, what is the correct way?但是,如果我希望使用基类构造函数设置值,正确的方法是什么?
Easiest and best: just call the initializers in each base!最简单也是最好的:只需调用每个基类中的初始化程序即可!
class Derv(Base1, Base2):
def __init__(self, x, y):
Base1.__init__(self, x)
Base2.__init__(self, y)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.