Introduction to Inheritance
Inheritance allows a class to inherit attributes and methods from another class. The class that inherits is called a child class (or subclass), and the class being inherited from is called a parent class (or superclass).
Inheritance promotes code reuse and helps model "is-a" relationships. For example, a Dog is an Animal, so Dog can inherit from Animal.
Basic Inheritance
To create a child class, put the parent class name in parentheses after the class name:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} makes a sound")
class Dog(Animal):
def speak(self):
print(f"{self.name} barks")
class Cat(Animal):
def speak(self):
print(f"{self.name} meows")
dog = Dog("Buddy")
cat = Cat("Whiskers")
dog.speak()
cat.speak()
Overriding Methods
Child classes can override parent methods by defining a method with the same name:
class Shape:
def area(self):
return 0
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14159 * self.radius ** 2
rect = Rectangle(5, 3)
print(rect.area())
circle = Circle(4)
print(circle.area())
Using super()
The super() function allows you to call parent class methods from a child class:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
print(f"I'm {self.name}, {self.age} years old")
class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age)
self.student_id = student_id
def introduce(self):
super().introduce()
print(f"My student ID is {self.student_id}")
student = Student("Alice", 20, "S123")
student.introduce()
Best Practices
✅ Inheritance Tips
• Use inheritance for "is-a" relationships
• Override methods to provide specific behavior
• Use super() to call parent methods
• Don't overuse inheritance - composition is sometimes better
• Keep inheritance hierarchies shallow