It’s possible for a class to inherit methods from multiple superclasses.
Typically, a subclass IS a kind of the superclass. For example, if Tiger is a subclass of Cat, this is because a “Tiger” literally is a kind of “Cat“.
In this example, a SmartPhone is a Phone, but it’s also a Camera.
class Phone:
def ring(self):
print("Trrrrring!")
class Camera:
def snap(selff):
print("Photo taken.")
class SmartPhone(Phone, Camera):
pass
s1 = SmartPhone()
s1.ring()
s1.snap()
Trrrrring!
Photo taken.
Class Hierarchies
It’s possible to create entire hierarchies of classes.
In this example, the C3PO class is a subclass of Cyborg, which is a subclass of both Machine and Person.
class Machine:
pass
class Person:
pass
class Cyborg(Person, Machine):
pass
class C3P0(Cyborg):
pass
Method Resolution
If you create a whole hierarchy of classes, and then create an object from one of the classes, and call a particular method of the object, how does Python know which method to run?
The method may come from the class or any of its superclassses. There may even be multiple methods with the same name.
Python will search classes for the method starting at the bottom of the class hierarchy, and working from left to right in cases where a subclass has multiple superclasses.
You can obtain the order classes will be searched to resolve a method call, using the mro() (method resolution order) class method.
class Machine:
def identify(self):
print("I am a machine")
class Person:
def identify(self):
print("I am a human being")
class Cyborg(Person, Machine):
pass
class C3P0(Cyborg):
pass
robot = C3P0()
robot.identify()
print(C3P0.mro())
I am a human being
[<class '__main__.C3P0'>, <class '__main__.Cyborg'>, <class '__main__.Person'>, <class '__main__.Machine'>, <class 'object'>]
In this case, when a method of the C3P0 object is called, first the C3P0 class is checked, then the Cyborg superclass, then the Person superclass, then the Machine class.
If the method has still not been found, the object class is checked. object is the ultimate superclass of all classes in Python.
Leave a Reply