Inheritance and data hiding

Inheritance and Data Hiding in Python

As the word “Inheritance” is giving you the intuition behind it i.e, inheriting the properties from one thing into another. So, in a programming language, one class is inheriting the properties of another class in order to make reusability of code.
The class which is deriving the functionality from another class is known as “subclass” or “derived class ” or “child class” and from the class which inheriting the properties is known as “Superclass” or “Parent class”.
Let’s dive into the example of how to do inheritance in Python. We are following the same example as in the previous blog of that company and employees.

1. How to perform an inheritance?

Creating a Parent class

Creating a  derived class

In this section, we are creating a class(Employee) which is inherited from the above class(company). To make a derived class we have to pass the name of the Parent(super class) in the derived class.
We are creating a new function of a derived class as well.

You will see here constructor function of a derived class is called while creating an object of subclass because we are inheriting all the properties of the parent class.

2. How to access the parent class variable or overwriting functions/constructor?

Changing the derived class(employee)

In this section, we are overwriting the constructor function and how to access the parent class members.

Here, we have done using the parent class name, but we can also do that using the super keyword.

Data Hiding

Data Hiding is also one of the concepts of object-oriented programming. In data hiding, we are trying to abstract the information from the end user.
In python, a hidden variable/function is created using “__” in front of a variable/function name. Hidden variable means we can’t access that variable outside the class.
Let’s see with the help of an example of how to create a hidden variable.

Creating a hidden variable

Creating a hidden function

Hope it gives you a better understanding of inheritance, data hiding and how to perform it in Python.
Stay tuned! Keep learning intermediate level Python with us. We have lots of amazing stuff for you.

Close Menu