Python Object Oriented Programming | Inheritance

Inheritance provides a way to share functionality between classes.
Imagine three classes, Motor, Car, and Truck. Although they may differ in some ways (only Car might have the method taxi), they are likely to be similar in others (all having the attributes color and name).

This similarity can be expressed by making them all inherit from a superclass Vehicle, which contains the shared functionality.

To inherit a class from another class, put the superclass name in parentheses after the class name.

Example:

class Vehicle: 
	def __init__(self, name, color):
		self.name = name
		self.color = color

class Motor(Vehicle):
	def honda(self):
		print("This is a Honda")

class Car(Vehicle):
	def taxi(self):
		print("Cars can be taxis!")

audi_taxi = Car("AudiTaxi", "yellow")
print(audi_taxi.color)
audi_taxi.taxi()

The terminal output will be:

ddn_ro@linux:~/Desktop$ python file.py
yellow
Cars can be taxis!
ddn_ro@linux:~/Desktop$

Note:

  • A class that inherits from another class is called a subclass.
  • A class that is inherited from is called a superclass.
  • If a class inherits from another with the same attributes or methods, it overrides them.

Example:

class Vehicle: 
	def __init__(self, name, color):
		self.name = name
		self.color = color
		
	def taxi(self):
		print("Cars can be taxis!")
		
class Car(Vehicle):
	def taxi(self):
		print("Automobils are great cars!")
		
audi = Car("A4", "black")
audi.taxi()

The terminal output will be:

ddn_ro@linux:~/Desktop$ python file.py
Automobils are great cars!
ddn_ro@linux:~/Desktop$

In the example above, Vehicle is the superclass, Car is the subclass.

Inheritance can also be indirect. One class can inherit from another, and that class can inherit from a third class.

Example:

class A:
	def method(self):
		print("A method")

class B(A):
	def another_method(self):
		print("B method")

class C(B):
	def third_method(self):
		print("C method")

c = C()
c.method()
c.another_method()
c.third_method()

The terminal output will be:

ddn_ro@linux:~/Desktop$ python file.py
A method
B method
C method
ddn_ro@linux:~/Desktop$

Note:
Circular inheritance is not possible.

The function super is a useful inheritance-related function that refers to the parent class. It can be used to find the method with a certain name in an object’s superclass.

Example:

class A:
    def spam(self):
        print(1)

class B(A):
    def spam(self):
        print(2)
        super().spam()

B().spam()

The terminal output will be:

>>>
2
1 
>>>

Note:
The super().spam() calls the spam method of the superclass. The above code will work just in Python 3. In Python 2 the error TypeError: super() takes at least 1 argument (0 given).

Leave a Reply