Introduction to Python Inheritance
Python Inheritance
Inheritance is a mechanism that allows a class to inherit the properties and methods of another class.
The class that inherits is called the "subclass"
or "derived class,"
and the class being inherited from is called the "superclass"
or "base class."
Inheritance facilitates code reuse and allows for the creation of a hierarchical structure of classes.
As an example:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} is making a sound.")
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed
def speak(self):
print(f"{self.name} is barking.")
# Creating objects of the classes
animal = Animal("Generic Animal")
dog = Dog("Buddy", "Labrador")
# Calling object methods
animal.speak() # Output: Generic Animal is making a sound.
dog.speak() # Output: Buddy is barking.
In this example:
- We have a superclass Animal with an
__init__()
method that takes aname
parameter and sets thename
attribute. It also has aspeak()
method that prints a generic sound.
- We define a subclass
Dog
that inherits fromAnimal
using parentheses in the class definition (class Dog(Animal)
). - The
Dog
class has its own__init__()
method that takes additional name andbreed
parameters. - It calls the superclass's
__init__()
method using thesuper()
function to set the name attribute, and also sets thebreed
attribute specific to the Dog class. - The Dog class overrides the
speak()
method of the superclass and provides its own implementation.
Method Overriding
Inheritance allows subclasses to override methods inherited from the superclass.
This means that a subclass can provide its own implementation of a method defined in the superclass. When the method is called on an object of the subclass, the overridden method in the subclass is executed instead of the superclass's method.
As an example:
class Animal:
def speak(self):
print("Generic animal sound.")
class Cat(Animal):
def speak(self):
print("Meow!")
cat = Cat()
cat.speak() # Output: Meow!
In this example:
- The
Cat
class overrides thespeak()
method inherited from theAnimal
class and provides its own implementation. - When we call the
speak()
method on aCat
object, it prints "Meow!" instead of the generic animal sound.
Multiple Inheritance
Python supports multiple inheritance, which means a subclass can inherit from multiple superclasses.
This allows the subclass to inherit attributes and methods from multiple sources. To specify multiple superclasses, you list them separated by commas in the class definition.
As an example:
class A:
def method_a(self):
print("Method A from class A.")
class B:
def method_b(self):
print("Method B from class B.")
class C(A, B):
def method_c(self):
print("Method C from class C.")
c = C()
c.method_a() # Output: Method A from class A.
c.method_b() # Output: Method B from class B.
c.method_c() # Output: Method C from class C.
In this example:
- The class
C
inherits from bothA
andB
. - As a result, the object c of class
C
has access to methods from bothA
andB
, as well as its ownmethod_c()
.
Method Resolution Order (MRO)
In cases where multiple inheritance is used, the order in which superclasses are listed becomes important.
The order determines the method resolution order, i.e., the order in which Python searches for a method when it is invoked on an object. Python follows the C3 linearization algorithm to determine the MRO. You can access the MRO of a class using the __mro__
attribute.
As an example:
class A:
pass
class B(A):
pass
class C(A):
pass
class D(B, C):
pass
print(D.__mro__) # Output: (<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>)
In this example:
- The
D
class inherits from bothB
andC
, both of which inherit fromA
. - The MRO of
D
is determined asD, B, C, A, object
.