In this article we will learn about Inheritance in Python.
In Inheritance, we derive new class from an existing class.
New here ? — Learn python from scratch
Inheritance is a very powerful concept in object-oriented programing.
Let’s understand by an example:
Let us say that the online shopping app wants to sell different types of phones:
- Feature phones and Smartphones
The below are the class diagrams for both the classes:
We can see that both the class have a lot in common. This is because they both are ultimately phones and each is just a special type of phone.
Since both the classes are of type phone, we can create a phone class with the common attributes and methods and make these two classes inherit those attributes and behavior, as shown:When a class inherits from another class, then those classes are said to have an inheritance relationship. The class which is inheriting is called the child/sub/derived class and the class which is getting inherited is called the parent/super/base class. Inheritance is also called as “is-A” relationship.
In our example, FeaturePhone is inheriting the Phone and SmartPhone is inheriting the Phone class (SmartPhone “is-A” phone, FeaturePhone “is-A” phone). So Phone is the parent class and FeaturePhone and SmartPhone are derived classes.
Advantages of Inheritence
There are three main advantages of inheritance:
- We can keep common properties in a single place. Thus any changes needs to be made need not be repeated.
- Inheritance encourages code reuse thus saving us time.
- If we want to add a new type of phone later on, we can simply inherit the Phone class instead of writing it from scratch.
To create an inheritance relationship between the classes, mention the name of the parent class in brackets as shown: class Phone:
def __init__(self, price, brand, camera): self.price = price self.brand = brand self.camera = camera def buy(self): print ("Buying a phone") def return_phone(self): print ("Returning a phone") class FeaturePhone(Phone): pass class SmartPhone(Phone): pass FeaturePhone(10000,"Apple","13px").buy()
What gets Inherited?
When we have a inheritance relationship, the attributes and behaviors get inherited, just like a child inherits certain attributes and behaviours from its parent.Unlike other languages, private variables get inherited in Python.
A child class can access everything a parent has, but a parent class cannot access anything from the child class.
Types of Inheritance
Inheritance can come in many forms as below:
End of inheritance in python article
Thankyou for reading the full article, if you have any question regarding the article please comment below.