Inheritance allows a class to inherit attributes and methods from another class. This promotes code reuse and creates logical hierarchies.
What is inheritance?
The parent class (superclass or base class) provides common functionality.
The child class (subclass or derived class) inherits and can extend or override it.
Define a parent class:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print("Some generic sound")
def info(self):
print(f"This is {self.name}")
Create a child class with inheritance:
class Dog(Animal):
pass
Now Dog inherits everything from Animal:
my_dog = Dog("Buddy")
my_dog.info() # This is Buddy
my_dog.speak() # Some generic sound
Extending the child class
Add new methods or attributes specific to the child:
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # Call parent __init__
self.breed = breed
def speak(self):
print("Woof!")
def fetch(self):
print("Fetching the ball!")
Usage:
dog = Dog("Buddy", "Golden Retriever")
dog.info() # This is Buddy
dog.speak() # Woof!
dog.fetch() # Fetching the ball!
print(dog.breed) # Golden Retriever
super() calls the parent method (useful in __init__ and overrides).
Overriding methods
The child can replace a parent method completely (as speak does above).
Multiple child classes
class Cat(Animal):
def speak(self):
print("Meow!")
cat = Cat("Luna")
cat.info() # This is Luna
cat.speak() # Meow!
Both Dog and Cat share info from Animal but have their own speak.
Simple examples
Vehicle hierarchy:
class Vehicle:
def __init__(self, brand):
self.brand = brand
def start(self):
print("Engine started")
class Car(Vehicle):
def drive(self):
print("Driving on roads")
class Boat(Vehicle):
def sail(self):
print("Sailing on water")
car = Car("Toyota")
car.start() # Engine started
car.drive() # Driving on roads
Important notes
- Use
super()to access parent methods. - A child class can inherit from only one parent in basic inheritance (single inheritance).
- Inheritance creates "is-a" relationships (Dog is an Animal).
- Keep inheritance shallow for readability.
Quick summary
- Child classes inherit from parent classes with
(Parent). - Use
super()to call parent methods. - Override methods to customize behavior.
- Add new methods for child-specific features.
- Inheritance reduces code duplication.
Practice building small class hierarchies. Inheritance helps create organized and reusable code in Python programs.
Top comments (0)