You can inherit as many classes as you need, building up functionality as you go. For example, you could have a class animalia, a subclass chordata, a sub-subclass mammalia, and a sub-sub-subclass homosapiens. Each one is more specific than its parent. However, an interesting addition in Python is the ability to have multiple inheritanceto take functionality from two classes simultaneously.
Again, this is best shown in code:
print "We're driving..." class timemachine(object): def timeTravel(self):
print "Traveling through time... "
class delorian(car,timemachine): pass mydelorian = delorian() mydelorian.drive() mydelorian.timeTravel()
In that example, we have a class car and a class timemachine. Both work by themselves, so you can have a car and drive around in it or a time machine and travel through time with it. However, we also have a delorian class that inherits from car and timemachine. As you can see, it is able to call both drive() (inherited from car) and timeTravel() (inherited from timemachine).
This introduces another interesting problem: What happens if both car and timemachine have a refuel() function? The answer is that Python picks the correct function to use based on the order in which you listed the parent classes. In the previous code, we use class delorian(car,timemachine) , which means "inherit from car and then from timemachine." As a result, if both classes had a refuel() function, Python would pick car.refuel() .
This situation becomes more complex when further inheritance is involved. That is, if car inherits its refuel() method from vehicle, Python still chooses it. What happens behind the scenes is that Python picks the first class you inherited from and searches it and all its parent classes for a matching method call. If it finds none, it goes to the next class and checks it and its parents. This process repeats until it finds a class that has the required method.
Was this article helpful?