如何从多个父类继承同名变量?

2024-09-28 22:29:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我遇到了一些关于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 = {}
    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上的博客http://python-history.blogspot.com/2010/06/method-resolution-order.html并观看了Raymond Hettinger的2015年PyCon视频super is super之后,我发现TestChild类只继承了TestFather的path变量,而完全忽略了TestMother的path变量。在

我的问题是,TestChild是否有办法使用其双亲各自的路径,而不是只选择MRO更高的路径。我知道更改变量名可以做到这一点,但正如Raymond所说,必须有更好的方法。在


Tags: topathselfobjectinitdefdictclass
1条回答
网友
1楼 · 发布于 2024-09-28 22:29:09

TestChild不能隐式地继承这两个,因为存在明显的名称冲突:TestChild.path不能同时有两个值。由于您还没有描述TestChild访问这两个值所需的语义,所以我不确定解决方案真正需要什么。在

但是,可以在函数上扩展,将名称存储在TestChild中,但是您可能喜欢两个字符串的列表?在

相关问题 更多 >