Reputation: 109
Say I have a base class Person
and two derived classes Footballer
and Musician
.
Obviously a person can be both a footballer and a musician, so maybe I want a third class called FootballerAndMusician
, but this class will just be a combination of the two other classes (there will not be conflicts: the two derived classes only override some specific things, and nothing in Musician
overrides that which is overriden in Footballer
, and vice versa).
What is the appropiate way to implement this pattern in Python that avoids having to repeat the code in the two derived classes in a third class (Imagine if I had to do this with several classes…)?
Basically, I want to implement many derived classes to Person
, and then easily be able to combine them as long as there aren't conflicts.
How is this designed in Python?
Upvotes: 0
Views: 421
Reputation: 9617
This is called Multiple Inheritance, and in Python this looks like this
class FootballerAndMusician(Footballer, Musician):
# your specific class code goes here, like
Now that class gets access to all the methods of both of the superclasses.
There's some subtle complexities with the order in which methods are looked up. In this simple case, though, it's just "left to right". So if both Footballer
and Musician
have a method called play
then in the example above your FootballerAndMusician
would use the Footballer
version.
Note that multiple inheritance can get complex and messy quickly, so you should really use it sparingly. I would suggest avoiding it if it's just in order to create some big "taxonomy".
Upvotes: 2
Reputation: 153
Multiple inheritance is what you're looking for.
Class Base1:
(body_1)
Class Base2:
(body_2)
Class Derived(Base1, Base2):
(body_3)
As long as your Base classes Footballer
and Musician
don't interfere with the other's methods, you're good to go.
Additionally, if you need to explicitly use the constructor,
Class Derived(Base1, Base2):
def __init__(self, args):
super(Derived, self).__init__(args)
Upvotes: 1
Reputation: 531075
It's quite simple:
class FootballerAndMusician(Footballer, Musician):
pass
This assumes, of course, that both Footballer
and Musician
(and Person
) are correctly designed to allow for multiple inheritance. See https://rhettinger.wordpress.com/2011/05/26/super-considered-super/ for advice on using super
correctly.
Upvotes: 1