#
Code Crafter IT Innovation
Loading...
  • Bansal Computer Center
  • punjabedu.bansalcenter.com

Python Inheritance

Hello
Hello

Hello


Single Inheritance

Definition

Use:

Used when only one parent class is needed to provide properties/methods to a child.

Example:


# Parent class
class Parent:
    def __init__(self, name):
        self.name = name
    
    def display(self):
        print(f"Parent name: {self.name}")

# Child class inheriting from Parent
class Child(Parent):
    def greet(self):
        print(f"Hello, I am {self.name}'s child.")

# Usage
obj = Child("Mayank")
obj.display()  # Inherited method
obj.greet()    # Child's own method

Key Points:



Multiple Inheritance

Definition

Use:

Combines features from multiple classes.

Example:


class Father:
    def skill(self):
        print("Father: Driving")

class Mother:
    def skill(self):
        print("Mother: Cooking")

class Child(Father, Mother):  # Multiple Inheritance
    def extra_skill(self):
        print("Child: Coding")

# Usage
obj = Child()
obj.skill()       # Output: Father: Driving (MRO -> Father first)
obj.extra_skill()
print(Child.mro())  # Shows MRO order

Key Points:



Multilevel Inheritance

Definition

Use:

Passes features down multiple generations.

Example:


class Grandparent:
    def property(self):
        print("Grandparent: Land")

class Parent(Grandparent):
    def house(self):
        print("Parent: House")

class Child(Parent):
    def car(self):
        print("Child: Car")

# Usage
obj = Child()
obj.property()  # From Grandparent
obj.house()     # From Parent
obj.car()       # From Child

Key Points:



Hybrid Inheritance

Definition

Example:


class School:
    def school_info(self):
        print("This is the School class")

class Student(School):
    def student_info(self):
        print("This is the Student class")

class Sports:
    def sports_info(self):
        print("This is the Sports class")

class SportsStudent(Student, Sports):
    def sportstudent_info(self):
        print("This is the Sports Student class")

ss = SportsStudent()
ss.school_info()       # From School
ss.student_info()      # From Student
ss.sports_info()       # From Sports
ss.sportstudent_info() # From SportsStudent
  


Hierarchical Inheritance

Definition

Use:

One base class is used for multiple specialized classes.

Example:


class Parent:
    def common(self):
        print("Common feature for all children")

class Child1(Parent):
    def feature1(self):
        print("Child1: Drawing")

class Child2(Parent):
    def feature2(self):
        print("Child2: Singing")

# Usage
obj1 = Child1()
obj2 = Child2()

obj1.common()
obj1.feature1()

obj2.common()
obj2.feature2()

Key Points:


Hello

What students Say?

Here are the stdudents...

#

Contact Us

Empower your tech dreams with us. Get in touch!

  • #
  • #
  • #
  • #
  • #