简体   繁体   中英

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. I can do something like this, but I am quite sure this is not very 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! And by the way: Classes A and B should not depend on each other.

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. When you call supper (Python 3), the __init__ of the first class in the mro list will be called. That __init__ is also expected to contain another super() so that the __init__ of the next class in the mro also gets called.

In your case, the mro list should be [A, B] . So the __init__ of A must contain an invocation of super so that the __init__ of B is also get called.

The problems here are:

  • You want A and B not to depend of each other. The use of super needs an mro list, which does not satisfy this requirement as I explained above.
  • 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 .

So it seems to me that super cannot help in this situation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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