Inheritance in Python

 Inheritance in Python


Inheritance is a fundamental concept in object-oriented programming (OOP) where a class (subclass or derived class) inherits attributes and methods from another class (superclass or base class). This allows the subclass to reuse the code of the superclass and extend its functionality. In Python, inheritance is achieved by specifying the name of the base class(es) inside parentheses after the subclass name.


Types of Inheritance:


1. Single Inheritance:



In single inheritance, a subclass inherits from only one superclass.

class Parent:
    def __init__(self, name):
        self.name = name
class Child(Parent):
    def __init__(self, name, age):
        super().__init__(name)
        self.age = age
# Example usage
child = Child("Prathamesh", 20)
print("Name  is:",child.name)  
print("Age is:", child.age)   

Explanation of Code:
his code demonstrates inheritance in Python using constructors and the super() function.

Parent Class (Parent):

The Parent class has a constructor (__init__) that takes a name parameter and initializes the name attribute.
Child Class (Child):

The Child class inherits from the Parent class (Child(Parent)).
It defines its own constructor (__init__) that takes two parameters: name and age.
Inside the Child class constructor, super().__init__(name) is called to invoke the constructor of the superclass (Parent). This initializes the name attribute inherited from the Parent class.
Additionally, the age attribute is initialized with the value passed to the constructor.
Example Usage:

An instance of the Child class is created with the name "Prathamesh" and age 20.
The name and age attributes of the child object are then printed to verify the initialization.
This code demonstrates how a subclass (Child) can inherit attributes from its superclass (Parent) and extend its functionality by adding new attributes (age) while still utilizing the superclass constructor to initialize common attributes.

Without using __init__Method:
class Parent:
    def set_name(self, name):
        self.name = name

class Child(Parent):
    def set_name_age(self, name, age):
        self.set_name(name)
        self.age = age

# Example usage
child = Child()
child.set_name_age("Prathamesh", 20)

print("Name is:", child.name)  
print("Age is:", child.age)  



2.    Multiple Inheritance:

In multiple inheritance, a subclass inherits from more than one superclass.

For Example,

class Father:

    def __init__(self, father_name):

        self.father_name = father_name


class Mother:

    def __init__(self, mother_name):

        self.mother_name = mother_name


class Child(Father, Mother):

    def __init__(self, name, father_name, mother_name):

        super().__init__(father_name)

        Mother.__init__(self, mother_name)  # Specify superclass explicitly

        self.name = name


# Example usage

child = Child("Sundar", "Sanskar", "Maya")

print("Child Name is:",child.name)         

print("Father's Name is:",child.father_name)  

print("Mother's Name is:",child.mother_name)  

Explanation,
Father class: Defines the Father class with a constructor that initializes the father_name attribute.

Mother class: Defines the Mother class with a constructor that initializes the mother_name attribute.

Child class: Inherits from both the Father and Mother classes. It has its constructor that initializes the name attribute along with invoking the constructors of the Father and Mother classes using super() and Mother.__init__().

Example usage: Creates an instance of the Child class named child, passing values for the child's name, father's name, and mother's name. Then, it prints out the child's name, father's name, and mother's name using the attributes of the child object.

The super() function is used to call the constructor of the immediate superclass (Father) to initialize the father_name attribute. Then, Mother.__init__() is explicitly called to initialize the mother_name attribute because Mother is not the immediate superclass (multiple inheritance). Finally, the child's name is initialized directly within the Child class constructor.

Without Using __init__Method:

class Father:

    def set_father_name(self, father_name):

        self.father_name = father_name


class Mother:

    def set_mother_name(self, mother_name):

        self.mother_name = mother_name


class Child(Father, Mother):

    def set_names(self, name, father_name, mother_name):

        self.set_father_name(father_name)

        self.set_mother_name(mother_name)

        self.name = name


# Example usage

child = Child()

child.set_names("Sundar", "Sanskar", "Vidya")


print("Child Name is:", child.name)         

print("Father's Name is:", child.father_name)  

print("Mother's Name is:", child.mother_name)


3. Multilevel Inheritance:


In multilevel inheritance, a subclass inherits from a superclass, and another subclass inherits from the first subclass.

For Example,

class Grandparent:

    def __init__(self, name):

        self.name = name


class Parent(Grandparent):

    pass


class Child(Parent):

    def __init__(self, name, age):

        super().__init__(name)

        self.age = age


# Example usage

child = Child("Mahesh", 25)

print("Name is:",child.name)  

print("Age is:",child.age)   

Grandparent class: Defines the Grandparent class with a constructor that initializes the name attribute.
Parent class: Inherits from the Grandparent class. It does not have its constructor, so it inherits the constructor from the Grandparent class.
Child class: Inherits from the Parent class. It has its constructor that initializes the name attribute using super() to call the constructor of the immediate superclass (Parent). Additionally, it initializes the age attribute.
Example usage: Creates an instance of the Child class named child, passing values for the child's name and age. Then, it prints out the child's name and age using the attributes of the child object.
In this example, the Parent class acts as an intermediary between the Grandparent and Child classes, allowing inheritance of attributes and methods from Grandparent to Child.


Without Using __init__ Method:
class Grandparent:
    def set_name(self, name):
        self.name = name

class Parent(Grandparent):
    pass

class Child(Parent):
    def set_details(self, name, age):
        self.set_name(name)
        self.age = age

# Example usage
child = Child()
child.set_details("Mahesh", 25)

print("Name is:", child.name)  
print("Age is:", child.age)

4.    Hierarchical Inheritance:




In hierarchical inheritance, multiple subclasses inherit from the same superclass.

For example,

class Grandparent:

    def __init__(self, name):

        self.name = name


class Parent(Grandparent):

    pass


class Aunt(Grandparent):

    pass


# Example usage

parent = Parent("Mahendra")

aunt = Aunt("Chaya")

print("Parent Name is:",parent.name)  

print("Aunt Name is :",aunt.name)   

Explaination,

Grandparent class: Defines the Grandparent class with a constructor that initializes the name attribute.

Parent class: Inherits from the Grandparent class. It does not have its constructor, so it inherits the constructor from the Grandparent class.

Aunt class: Also inherits from the Grandparent class. It does not have its constructor, so it also inherits the constructor from the Grandparent class.

Example usage:

Creates an instance of the Parent class named parent and passes the name "Mahendra" to its constructor.

Creates an instance of the Aunt class named aunt and passes the name "Chaya" to its constructor.

Prints out the names of the parent and aunt using the name attribute of each object.

Both the Parent and Aunt classes inherit the name attribute from the Grandparent class, demonstrating single inheritance. However, they are separate instances of the class, each with its own set of attributes.

Without Using __init__Method:

class Grandparent:

    def set_name(self, name):

        self.name = name


class Parent(Grandparent):

    pass


class Aunt(Grandparent):

    pass


# Example usage

parent = Parent()

aunt = Aunt()

parent.set_name("Mahendra")

aunt.set_name("Chaya")


print("Parent Name is:", parent.name)

print("Aunt Name is :", aunt.name)


5.    Hybrid Inheritance:

Hybrid inheritance is a combination of two or more types of inheritance.

For Example,

class School:

    def func1(self, name):

        self.name = name



class Student1(School):

    def func2(self, name):

        self.name = name

        print("This function is in student 1.")


    def greet(self, wish):

        self.wish = wish

        print("Hello from student 1!")



class Student2(School):

    def func3(self, name):

        self.name = name

        print("This function is in student 2.")


    def calculate(self, x, y):

        return x + y



class Student3(Student1, Student2, School):  # Ensure Student3 inherits from Student2

    def func4(self, name):

        self.name = name

        print("This function is in student 3.")


    def display(self, message):

        print("Student 3 says:", message)



# Driver's code

object = Student3()

object.func1("Ramesh")  # Calling func1 from School

object.func2("Sundar")  # Calling func2 from Student1

object.greet("Good morning")  # Calling greet from Student1

print("Sum:", object.calculate(5, 3))  # Calling calculate from Student2

object.display("Have a nice day!")  # Calling display from Student3






टिप्पणी पोस्ट करा

1 टिप्पण्या

कृपया तुमच्या प्रियजनांना लेख शेअर करा आणि तुमचा अभिप्राय जरूर नोंदवा. 🙏 🙏