【问题标题】:How to inherit same name variables from multiple parent classes?如何从多个父类继承同名变量?
【发布时间】:2017-04-21 00:49:20
【问题描述】:

我遇到了一些关于 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视频超级棒后,我意识到TestChild类只继承了TestFather的path变量,而完全忽略了TestMother的path变量。

我的问题是,有没有办法让 TestChild 使用其两个父母各自的路径,而不是只采用具有更高 MRO 的路径。 我知道更改变量名可以解决问题,但作为雷蒙德说,一定有更好的办法。

【问题讨论】:

    标签: python inheritance method-resolution-order


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-06
      相关资源
      最近更新 更多