无法在多重继承Python中访问第二个父类的成员变量
我正在学习Python的多种继承。我有两个家长机器人和人类。他们是由半机械人班继承的。我可以访问头等舱IE,机器人的成员变量,但无法访问名为 human>的第二个基本的变量。
这是我的代码。
from abc import abstractmethod, ABC
class Robot(ABC):
def __init__(self):
self.computation_level = 70
@abstractmethod
def vacuum(self):
pass
class Human(ABC):
def __init__(self):
self.feelings_level = 60
@abstractmethod
def run(self):
pass
class Cyborg(Robot, Human):
def __init__(self):
super(Cyborg, self).__init__()
def vacuum(self):
print("nothing new in vacuum")
def run(self):
print("nothing new in run")
h_obj = Cyborg()
h_obj.vacuum()
h_obj.run()
print(h_obj.computation_level)
print(h_obj.feelings_level)
它返回以下输出,
nothing new in vacuum
nothing new in run
70
Traceback (most recent call last):
File "oop.py", line 49, in <module>
print(h_obj.feelings_level)
AttributeError: 'Cyborg' object has no attribute 'feelings_level'
我还检查了 cyborg.mro()的输出,
[<class '__main__.Cyborg'>, <class '__main__.Robot'>, <class '__main__.Human'>, <class 'abc.ABC'>, <class 'object'>]
在这种情况下,有任何方法可以访问第二个父级的成员变量, human 班级。
谢谢
I am learning multiple inheritance in Python. I have two parent classes Robot and Human. They are being inherited by Cyborg class. I can access the member variable in first class i.e, Robot but unable to access the variables in second BaseClass named Human.
Here is my code.
from abc import abstractmethod, ABC
class Robot(ABC):
def __init__(self):
self.computation_level = 70
@abstractmethod
def vacuum(self):
pass
class Human(ABC):
def __init__(self):
self.feelings_level = 60
@abstractmethod
def run(self):
pass
class Cyborg(Robot, Human):
def __init__(self):
super(Cyborg, self).__init__()
def vacuum(self):
print("nothing new in vacuum")
def run(self):
print("nothing new in run")
h_obj = Cyborg()
h_obj.vacuum()
h_obj.run()
print(h_obj.computation_level)
print(h_obj.feelings_level)
It returns the following output
nothing new in vacuum
nothing new in run
70
Traceback (most recent call last):
File "oop.py", line 49, in <module>
print(h_obj.feelings_level)
AttributeError: 'Cyborg' object has no attribute 'feelings_level'
I have also checked output of Cyborg.mro() which is
[<class '__main__.Cyborg'>, <class '__main__.Robot'>, <class '__main__.Human'>, <class 'abc.ABC'>, <class 'object'>]
Is there any way to access the member variables of second parent class in this case, Human class.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
也许可以帮助其他任何人,这是工作代码。
感谢@jsonharper
It maybe of help anyone else, here is the working code.
Thanks to @jsonharper