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 inheritance?

Creating a Parent class

class company:
    ## Class variable
    welcome_msg = 'Welcome to Robofied!'
    ## Constructor function called while creating object.
    def __init__(self,Profile):
        self.Profile = Profile
        print('Welcome to {} team!'.format(self.Profile))
    def office_hours(self,start_time,finish_time):
        ## How to access class variable inside function
        ## We can access variable passed to constructor function here as well.
        """This is because that variable is associated with object and self is basically for your understanding 
        we can say it represents object"""
        print('Welcome to {} team!'.format(self.Profile))
        ## variables inside the function only
        ## instance variable
        self.start_time = start_time
        self.finish_time = finish_time
        print('Your office hours will be ' + str((int(self.finish_time.split(':')[0]) - int(self.start_time.split(':')[0])))+ 
              ' hours.')

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.
class Employee(company):
    def isEmployee(self):
        return True

Creating an object using the derived class

obj1 = Employee("Data Scientist")
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.
Welcome to Data Scientist team!
## Accessing the function defined under new created class.
## Accessing the function of the parent class with the object created using 
## derived class.

Welcome to Robofied!
Welcome to Data Scientist team!
Your office hours will be 8 hours.
""" We can also access the class variables of parent class using derived 
class object """

'Welcome to Robofied!'

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.
class Employee(company):
    def __init__(self,Profile,Name):
        ## Overwriting the base class attribute
        company.Profile = Profile
        self.Name = Name
        ##company.Profile == self.Profile
        print('Hi {}! Welcome to {} team!'.format(self.Name,self.Profile))
    def isEmployee(self):
        return True
obj3 = Employee("Mean Stack Developer","Rajesh")
Hi Rajesh! Welcome to Mean Stack Developer team!
Here, we have done using parent class name, but we can also do that using 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 how to create a hidden variable.

Creating a hidden variable

class company:
    ## creating hidden variable
    __hiddenvariable = 5
    def add_value(self):
        self.__hiddenvariable +=2
obj1 = company()
""" Here calling the function which is accessing the hidden varible
Here we are able to access the hidden variable because function is 
defined inside class only. """

Here we are trying to access hidden variable using object and it is giving the error because we can’t access the hidden variable outside class.
AttributeError                            Traceback (most recent call last)
<ipython-input-43-7a5f402526c5> in <module>()
----> 1 obj1.__hiddenvariable

AttributeError: 'company' object has no attribute '__hiddenvariable'

Creating a hidden function

class company:
    __hiddenvariable = 5
    def __add_value(self):
        self.__hiddenvariable +=2
obj2 = company()
Here we are trying to access hidden function using object and it is giving the error because we can’t access the hidden function outside class.
AttributeError                            Traceback (most recent call last)
<ipython-input-46-7e241d4997ea> in <module>()
----> 1 obj2.__add_value()

AttributeError: 'company' object has no attribute '__add_value'
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.

Leave a Comment

Your email address will not be published. Required fields are marked *