Python 如何从多个父类继承相同名称的变量?
我遇到了一些关于python多重继承的问题Python 如何从多个父类继承相同名称的变量?,python,inheritance,method-resolution-order,Python,Inheritance,Method Resolution Order,我遇到了一些关于python多重继承的问题 class TestFather(object): fathers = {} path = "/C" def __init__(self): super(TestFather, self).__init__() # self.fathers = file_to_dict(self.path) class TestMother(object): mothers = {} pat
class TestFather(object):
fathers = {}
path = "/C"
def __init__(self):
super(TestFather, self).__init__()
# self.fathers = file_to_dict(self.path)
class TestMother(object):
mothers = {}
path = "/D"
def __init__(self):
super(TestMother, self).__init__()
# self.mothers = file_to_dict(self.path)
class TestChild(TestFather, TestMother):
def __init__(self):
super(TestChild, self).__init__()
t = TestChild()
help(t)
变量路径将存储母亲和父亲的文件目录。当我打印出父亲和母亲的字典时,我注意到母亲的字典以某种方式从父亲那里获取了所有信息。在阅读Guido关于MRO的博客并观看Raymond Hettinger的2015 PyCon视频super is super之后,我意识到TestChild类只继承TestFather的路径变量,而完全忽略TestMother的路径变量
我的问题是,TestChild是否有办法使用其双亲各自的路径,而不是只使用MRO较高的路径。我知道更改变量名可以做到这一点,但正如Raymond所说,必须有更好的方法。TestChild不能隐式继承这两个路径,由于明显的名称冲突:TestChild.path不能同时具有两个值。由于您尚未描述TestChild访问这两个值所需的语义,因此我不确定解决方案真正需要什么
但是,您可以扩展\uuuu init\uuuu函数,在TestChild中存储您喜欢的名称——可能是两个字符串的列表