Inheritance allows a class (child) to inherit properties and behavior (variables & methods) from another class (parent).
โ It promotes code reusability and hierarchical relationships โ just like how a child inherits traits from parents in real life.
Parent Class: Vehicle
๐
Child Classes: Car
, Bike
They all share common features (like engine, speed) but also have unique features.
class Parent:
# parent class
class Child(Parent):
# child class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} makes a sound.")
class Dog(Animal):
def bark(self):
print(f"{self.name} barks!")
dog1 = Dog("Buddy")
dog1.speak() # Inherited from Animal
dog1.bark() # Defined in Dog
One child inherits from one parent.