Chapter 9: Object-Oriented Programming / Lesson 49

Inheritance

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:

inheritance.py
# Parent class class Animal: def __init__(self, name): self.name = name def speak(self): print(f"{self.name} makes a sound") # Child class class Dog(Animal): def speak(self): print(f"{self.name} barks") class Cat(Animal): def speak(self): print(f"{self.name} meows") # Create objects dog = Dog("Buddy") cat = Cat("Whiskers") dog.speak() # Buddy barks cat.speak() # Whiskers meows

Overriding Methods

Child classes can override parent methods by defining a method with the same name:

overriding.py
class Shape: def area(self): return 0 class Rectangle(Shape): def __init__(self, width, height): self.width = width self.height = height def area(self): # Override parent method return self.width * self.height class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): # Override parent method return 3.14159 * self.radius ** 2 rect = Rectangle(5, 3) print(rect.area()) # 15 circle = Circle(4) print(circle.area()) # 50.27

Using super()

The super() function allows you to call parent class methods from a child class:

super_function.py
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) # Call parent __init__ self.student_id = student_id def introduce(self): super().introduce() # Call parent method 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

🎉

Lesson Complete!

Great work! Continue to the next lesson.

main.py
📤 Output
Click "Run" to execute...