Книга: Fedora™ Unleashed, 2008 edition

Multiple Inheritance

Multiple Inheritance

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 capability to have multiple inheritance — to take functionality from two classes simultaneously.

Again, this is best shown in code:

class car(object):
 def drive(self):
  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, you can see 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, there is also 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. The previous code used 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 from which you inherited 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.

Оглавление книги


Генерация: 0.902. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз