Inheritance in Python allows a class (called a child class or subclass) to derive or inherit the attributes and methods from another class (called a parent class or base class). This concept promotes code reuse and makes it easier to create and maintain applications by enabling hierarchical class relationships.
Key Features of Inheritance
Child Class Can Access Parent Class Members:
Attributes and methods defined in the parent class are accessible in the child class.
Child Class Can Override Parent Class Members:
A child class can redefine methods or attributes of the parent class.
Support for Multiple Inheritance:
Python allows a child class to inherit from multiple parent classes.
class ParentClass:
def __init__(self, value):
self.value = value
def parent_method(self):
print("This is a method in the ParentClass")
# Inheriting ParentClass
class ChildClass(ParentClass):
def child_method(self):
print("This is a method in the ChildClass")
# Example usage
child = ChildClass(10)
child.parent_method() # Accessing parent method
child.child_method() # Accessing child method
Types of Inheritance in Python
class Parent:
pass
class Child(Parent):
pass
class Parent1:
pass
class Parent2:
pass
class Child(Parent1, Parent2):
pass
class GrandParent:
pass
class Parent(GrandParent):
pass
class Child(Parent):
pass
class Parent:
pass
class Child1(Parent):
pass
class Child2(Parent):
pass