【问题标题】:Elegant multiple inheritance in PythonPython中优雅的多重继承
【发布时间】:2013-07-12 08:01:38
【问题描述】:

我目前正在使用这种模式来创建一个类C,它继承自AB。我无法从C 调用super().__init__,因为我必须在AB 中执行相同的操作,并且意外参数会导致顶层出现问题。我觉得这不是很优雅。在 Python 中进行多重继承的正确方法是什么?我想查询mro 以查明超类是否需要参数是不寻常的?

class A:
    def __init__(self, something):
        self.a = X(something)

    def method_a(self):
        self.a.go()

    def method_ab(self):
        self.a.go2()


class B:
    def __init__(self, something):
        self.b = X(something)

    def method_b(self):
        self.b.go()

    def method_ab(self):
        self.b.go2()


class C(A, B):
    def __init__(self, something):
        self.a_ = A(something)
        self.b_ = B(something)

    @property
    def a(self):
        return self.a_.a

    @property
    def b(self):
        return self.b_.b

    def method_ab(self):
        for x in [self.a, self.b]:
            x.method_ab()

【问题讨论】:

  • 在您的最后一个示例中,您根本没有使用继承。我的意思是,是的C 继承了AB,但是类主体正在使用委托/组合(即执行class C: 不会改变类的行为,除了isinstance 检查[实际上是可以做一些技巧来使它们也能工作])
  • @Bakuriu:实际上,method_amethod_b 正在被继承……虽然我承认它并不优雅。请参阅下面的解决方案。
  • @delnan:是的,这完全相关!最重要的一段:“对于对象没有感兴趣的方法的情况(例如draw() 方法),我们需要编写一个保证在对象之前调用的根类。根类的职责只是简单地吃掉方法调用而不使用super()进行转发调用。”

标签: python python-3.x multiple-inheritance


【解决方案1】:

我发现的最佳解决方案是使用基类来吸收额外的参数:

class Base:
    def __init__(self, something):
        pass

    def method_ab(self):
        pass

class A(Base):
    def __init__(self, something):
        super().__init__(something)
        self.a = X(something)

    def method_a(self):
        self.a.go()

    def method_ab(self):
        super().method_ab()
        self.a.go()


class B(Base):
    def __init__(self, something):
        super().__init__(something)
        self.b = X(something)

    def method_b(self):
        self.b.go()

    def method_ab(self):
        super().method_ab()
        self.b.go()


class C(A, B):
    pass

【讨论】:

    猜你喜欢
    • 2011-06-11
    • 2020-12-18
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-26
    • 2021-05-16
    相关资源
    最近更新 更多