Inheritance is an essential and powerful aspect of object-oriented programming. The main advantage of inheritance is the reusability of code, which avoids the need to rewrite code from scratch.
What is Inheritance?
The process of inheriting methods or properties from the parent class into the child class is known as inheritance.
The child/derived/sub class is the class that inherits the properties.
The base/parent class is the class that has been inherited from. This is the existing class.
Example of inheritance in python
To demonstrate how inheritance is applied let's use a real-life situation.
A quadrilateral
is a two-dimensional figure with four sides. Therefore, let's call our parent class quadrilateral
.
class Quadrilateral:
def property(self):
Print("I am a quadrilateral with 4 sides and my total angles is 360 degrees")
class Square(Quadrilateral):
def square_property(self):
print("I am a square and I have 4 equal sides")
square = Square()
square.property()
square.square_property()
#Output:I am a quadrilateral with 4 sides and my total angles is 360 degrees
#Output:I am a square and I have 4 equal sides
According to the code, the base class is the Quadrilateral
. This is the existing class.
The Square
class is the subclass or the child class. This class inherits the properties of the Quadrilateral
class. Notice from the code we could access the properties of the Quadrilateral
class from the Square
class.
We can also use the issubclass()
method to check if a class is a child class of an existing class. If it returns True
then it is a subclass of the other class.
The isinstance()
method is also used to check the relationship between the object(square
) and the class(Square
). It will return True if the object(square
) is the instance of the class(Square
).
print(issubclass(Square, Quadrilateral)) # True
print(isintance(square, Square)) # True