Python Inheritance
33. Python Inheritance
1. What is Inheritance
Inheritance allows a class (child) to acquire properties and behaviors of another class (parent).
class Animal:
def eat(self):
print("Animal is eating")
class Dog(Animal):
pass
d = Dog()
d.eat() # Inherited methodPromotes code reusability and hierarchical design.
2. Single Inheritance
class Parent:
def show(self):
print("This is the parent class")
class Child(Parent):
pass
c = Child()
c.show()A child class inherits from one parent class.
3. Adding New Methods in Child Class
Child classes can extend functionality beyond the parent.
4. Method Overriding
Child class can redefine parent methods.
5. Using super() to Call Parent Method
super() invokes the parent class method within the child.
6. Multilevel Inheritance
Inheritance chain stretches across multiple levels.
7. Multiple Inheritance
A child class inherits from multiple parent classes.
8. Method Resolution Order (MRO)
MRO defines the order in which methods are resolved in inheritance.
9. Constructor Inheritance
Child constructors can call parent constructors using super().
10. Real-World Inheritance Example
Demonstrates inheritance in an object-oriented system.
Last updated