Welcome to a new tutorial on inheritance in python. Inheritance refers to the concept of inheriting behaviors of the existing class to the new classes or objects. It means many child classes can be derived from the child class with some or behaviors inherited. Child classes are also known as derived classes.
In OOP features common to all the classes are defined in the superclass (Base Class) and derived class inherits common features from the superclass. The main advantage of using this concept of inheritance in python is re-usability.
Let’s go with one example:
class Person: def __init__(self, name, age): self.name = name self.age = age def birthday(self): print('Happy birthday to you', self.name)
Now we are going to define Employee as being a class that inherits the class Person.
class Employee(Person): def __init__(self, name, age, id): super().__init__(name, age) self.id = id
Here, we have created a child class Employee inherited from superclass Person. Inside the __init__ method we reference the __init__() method defined in the class Person and used to initialize instances of that class (via the super().__init__() reference.
print('Employee') e = Employee('Denise', 51,44) e.birthday() Output: Happy birthday to you Denise
This page is contributed by Diwas. If you like AIHUB and would like to contribute, you can also write an article & mail your article to email@example.com . See your articles appearing on AI HUB platform and help other AI Enthusiast.