简体   繁体   English

Python:多重继承中的共享方法和属性

[英]Python: shared methods and attributes in multiple inheritance

I simply want to create a class which inherits attributes and methods from two parents.我只是想创建一个从两个父级继承属性和方法的类。 Let's just say the two parent classes are假设两个父类是

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

    def method_a(self):
        return self.a + 10


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

    def method_b(self):
        return self.b + 20

Then I am not sure how to create a subclass C which inherits both methods and attributes from its parents.然后我不知道如何创建一个从其父类继承方法和属性的子类 C。 I can do something like this, but I am quite sure this is not very pythonic...我可以做这样的事情,但我很确定这不是很pythonic......

class C(A, B):
    def __init__(self, a, b):
        A.__init__(self, a=a)
        B.__init__(self, b=b)

then I can do this without a problem那么我可以毫无问题地做到这一点

my_class = C(a=1, b=2)
print(my_class.a)
print(my_class.b)
print(my_class.method_a())
print(my_class.method_b())

I don't know how to set up super to inherit methods and attributes from both parents and I would appreciate any help!我不知道如何设置super来继承父母双方的方法和属性,我将不胜感激! And by the way: Classes A and B should not depend on each other.顺便说一句:A 类和 B 类不应相互依赖。

As far as I know, the way super works is that, based on the list of superclasses declared at the beginning of the subclass, an mro (method resolution order) list will be worked out.据我所知, super工作方式是,根据子类开头声明的超类列表,计算出一个mro (方法解析顺序)列表。 When you call supper (Python 3), the __init__ of the first class in the mro list will be called.当您调用supper (Python 3) 时,将调用mro列表中第一个类的__init__ That __init__ is also expected to contain another super() so that the __init__ of the next class in the mro also gets called. __init__也应该包含另一个super()以便mro下一个类的__init__也被调用。

In your case, the mro list should be [A, B] .在您的情况下, mro列表应该是[A, B] So the __init__ of A must contain an invocation of super so that the __init__ of B is also get called.所以A__init__必须包含对super的调用,以便B__init__也被调用。

The problems here are:这里的问题是:

  • You want A and B not to depend of each other.您希望AB不相互依赖。 The use of super needs an mro list, which does not satisfy this requirement as I explained above. super的使用需要一个mro列表,它不能满足我上面解释的这个要求。
  • The __init__ of C has 2 parameters while those of A and B have only 1. You may be able to pass a to A but I don't know if there's a way for you to pass b to B . C__init__有 2 个参数,而AB只有 1 个。您可以将a传递给A但我不知道是否有办法将b传递给B

So it seems to me that super cannot help in this situation.所以在我看来super在这种情况下无能为力。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM