Inheritance at a glance!
In the world of Object-Oriented Programming (OOP), Inheritance refers to the mechanism of the capability of a class to derive or extend the properties from another class in the run. This property enables the derived class to acquire the properties or traits of the base class.
Inheritance is considered one of the most important aspects of OOP because it serves the feature of reusability, thus making the piece of code more reliable.
Benefits of Inheritance
- Inheritance depicts relationships that resemble real-world scenarios.
- It provides the feature of re-usability which allows the user to add more features to the derived class without altering it.
- If a class Y inherits from class X, then automatically all the sub-classes of Y would inherit from class X.
Basic Terminologies of Inheritance
- Subclass/Derived class: It is a class that inherits the properties from another class (usually the base class).
- Superclass/Base class: It is the class from which other subclasses are derived.
- A derived class usually derives/inherits/extends the base class.
Python Inheritance Syntax
class SuperClassName: Body of Super class class DerivedClass_Name(SuperClass): Body of derived class
Python Inheritance Example
Let’s dive into the world of inheritance in Python with simple examples.
Step 1: Create a Base class
class Father: # The keyword 'self' is used to represent the instance of a class. # By using the "self" keyword we access the attributes and methods of the class in python. # The method "__init__" is called as a constructor in object oriented terminology. # This method is called when an object is created from a class. # it allows the class to initialize the attributes of the class. def __init__(self, name, lastname): self.name = name self.lastname = lastname def printname(self): print(self.name, self.lastname) # Use the Father class to create an object, and then execute the printname method: x = Father("Anees", "Mulani") x.printname()
Output: Anees Mulani
Step 2: Create a Derived class
# The subclass __init__() function overrides the inheritance of the base class __init__() function. class Son(Father): def __init__(self, name, lastname): Father.__init__(self, name, lastname) x = Son("Dev", "Bajaj") x.printname()
Output: Dev Bajaj
Use of super() function
By using the
super() function, you do not have to use the name of the parent element, it will automatically inherit the methods and properties from its parent.
class Father: def __init__(self, name, lastname): self.name = name self.lastname = lastname def printname(self): print(self.name, self.lastname) class Son(Father): def __init__(self, name, lastname): super().__init__(name, lastname) x = Student("Dev", "Bajaj") x.printname()
Output: Dev Bajaj