-4

I have the following class inheritance in Python:

A
|
B--D
|  |
C  E

What bothers me is that I have a lot of duplicate class methods in C and E. This can be avoided if I make E a child of C instead of D, but then I'd have to duplicate D's methods in E.

Is there a way for E to subclass both D and C so that E has functions from both C and D?

11
  • 5
    class E(C,D):...? Commented Dec 30, 2020 at 16:11
  • 2
    Yes, Python allows multiple inheritance. Commented Dec 30, 2020 at 16:12
  • 2
    or move shared code into another class and derive both from that Commented Dec 30, 2020 at 16:12
  • 2
    @SibbsGambling search for MRO, i.e method resolution order Commented Dec 30, 2020 at 16:13
  • 2
    If you are using super, every class should use super. The order in which each individual class's __init__ method is called depends on the final method resolution order. Commented Dec 30, 2020 at 16:13

5 Answers 5

3

You can make multiple inheritance. You have a lot of posibilities when you implement this, so it depends on your needs.

For example:

class E(C, D):
   pass

Check this out: https://www.programiz.com/python-programming/multiple-inheritance

Sign up to request clarification or add additional context in comments.

Comments

2

You can inherit from two classes at once:

class a(b, c):
    pass

So, if in b, thing1 = 123 and in c, thing2 = 64, a would have both of those variables.

>>> a.thing1
123
>>> a.thing2
64

But if class a is like this:

class a(b, c):
    thing3 = 42

Using dir(a), in the end of the huge list would appear:

'thing1', 'thing2', 'thing3'

Therefore, you can do this:

>>> a.thing3
42

But not this (I assume):

>>> c.thing3

Comments

1

You can certainly. Check out this resource https://pythonprogramminglanguage.com/multiple-inheritance/#:~:text=In%20Python%20a%20class%20can,concept%20from%20object%20orientated%20programming.

class A:
    pass

class B(A):
    pass

class C(B):
    pass

class D(B):
    pass

class E(C, D):
    pass

Comments

1

You can subclass multiple classes as follows

class C:
   pass
class D:
   pass
class E(C, D):
   pass

You may even create a mixin (which is just a class that's not meant to be used standalone) and put the common features there, and add that mixin to your classes that need those features.

What is a mixin, and why are they useful?

Comments

1

One of solutions is to extract methods duplicated in C and E to a new class F and let C and E inherit from F. In most cases it is called Mixin. Look at this answer for more explanation: https://stackoverflow.com/a/547714/3421655.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.