Inheritance in Python. Topic – 44

Inheritance in Python

Inheritance in Python is one of the core concepts of Python. Inheritance is a powerful mechanism that allows you to create new classes (called subclasses or derived classes) based on existing classes (called base classes or parent classes). Let’s understand through a story.

Imagine my family. There is my grandfather, then my father, and then me. Biologically speaking, my grandfather has some properties that are present in my father. My father also has some unique properties of his own. Now, I have some properties that I inherited from my father and some unique properties of my own. The interesting thing is that the new properties I have acquired did not require any modification of the properties present in my grandfather or father.

Inheritance works similarly. Let’s understand this first through an easy example.

Python
class A:
    def displayA(self):
        print("Welcome to Cyber Cript - A")

    
class B(A):
    def displayB(self):
        print("Welcome to Cyber Cript - B")


obj = B()

obj.displayB()
obj.displayA()
Output
Welcome to Cyber Cript - B
Welcome to Cyber Cript - A

Let’s see what we’ve done in this code. First, we created a class named “A”. Then we defined a method named displayA. Methods always accept a self keyword. And we added a print statement that prints a message.

Next, we created a “B” class in the same way. What the “B” class does is accept an “A” class. And the rest prints in the same way as the “A” class does.

Then we created an object of the “B” class. Look carefully, we created an object of the “B” class, not the “A” class. Then we called the displayB method from within the “B” class. But the interesting thing is that we also accessed the displayA() method using the “B” object. Look closely, we didn’t create any “A” class object. We accessed the “A” class using the object of “B”. This is inheritance

Consider a scenario where we have two classes: Employee and Developer. The Employee class represents a generic employee with a basic attribute named name. The Developer class represents a specific type of employee with additional attributes related to their programming skills, such as programming_language and experience_in_years.

Python
class Employee:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def details(self):
        print(f"Name: {self.name}; Age: {self.age}")

Assume I need to create a Developer class. The Developer class should include the name and age attributes (inherited from the parent class) and an additional attribute named language. There are two ways to approach this:

Copy-Paste Method:

We could simply create a new Developer class and copy-paste the name attribute definition from the Employee class. However, this is not a good approach as it leads to code duplication and makes maintenance difficult.

Inheritance Method:

As skilled Python developers, we’ll use the more appropriate approach of inheritance. We’ll create a Developer class and inherit the Employee class, leveraging the existing name attribute and adding the new language attribute.

Python
class Developer(Employee):
    def __init__(self, name, age, language):
        super().__init__(name, age)
        self.language = language


    def devDetails(self):
        print(f"Name: {self.name}; Age: {self.age}; Language: {self.language}")

dev = Developer("Arpan", 21, "Python")
dev.devDetails()
Output
Name: Arpan; Age: 21; Language: Python

In the Developer class, we added a constructor that takes name, age, and language as parameters. Inside this constructor, we call the superclass (Employee) constructor using super().__init__(name, age) to initialize the name and age attributes inherited from the Employee class.

Let’s see what is super() method. The super() function is a built-in function that returns the objects representing the parent class. It allows access to the parent class’s methods and attributes in the child class. The super() function is mainly used when passing parameters.

Now, we will create an object of the Developer class and access all its values through the dev object.

Now, let’s see a proper industry-level code. It’s may difficult to understand for you. But don’t worry after some practice you can do this. You also skip this industry-level code for now. Because inheritance is really tricky.

Python
class Employee:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def get_name(self):
        return self.name

    def set_name(self, new_name):
        self.name = new_name

    def get_age(self):
        return self.age

    def set_age(self, new_age):
        self.age = new_age


class Developer(Employee):
    def __init__(self, name, age, language):
        super().__init__(name, age)
        self.language = language

    def get_programming_language(self):
        return self.language

    def set_programming_language(self, new_language):
        self.language = new_language


# Creating an object of the Developer class
dev = Developer("Priti", 30, "Python")

# Accessing attributes using the object
print(dev.name)  # Output: Priti
print(dev.age)  # Output: 30
print(dev.language)  # Output: Python

# Accessing methods using the object
print(dev.get_programming_language())  # Output: Python

dev.set_programming_language("Javascript")
print(dev.get_programming_language())  # Output: Javascript
Output
Priti
30
Python
Python
Javascript

Types of inheritance:

  • Single inheritance
  • Multiple inheritance
  • Multilevel inheritance
  • Hierarchical Inheritance
  • Hybrid Inheritance

We will see the explanation and example of each type of inheritance in the later tutorials. And We also read super() method in detail.

Getters and Setters in python

Getters and Setters in Python

In OOPs languages, getters and setters are used to retrieve and update data. A getter….

I hope you understand “Inheritance in Python. Need guidance or have questions? Drop a comment below. Share your email for a personalized touch—I’ll send exclusive resources and answer queries. Let’s code together, creating efficient code and memorable learning moments! 🚀

Finite number of  lines code and infinite possibilities

Programmer, Arpan Bera

Leave a Reply

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

ABOUT ME
Arpan Bera

Coding is like Love – everyone can start, but only a few finish without errors

Keep Updated to our News and Blog