Inheritance
Build on existing classes
Inheritance is a powerful concept in object-oriented programming that helps you organize and reuse your code efficiently. Let's dive in and see how it works in Python!
Introduction
Imagine you're building a system with many similar things. Instead of writing code from scratch for each one, you can build on what you already have.
That's exactly what inheritance helps us do. It's a way to define new classes based on existing ones.
What is inheritance?
Inheritance is a mechanism that allows a new class (called a subclass or child class) to inherit properties and behaviors from an existing class (called a superclass or parent class).
- The child class gets all the attributes (variables) and methods (functions) of its parent.
- It can also add its own unique attributes and methods.
- It can even change (override) the methods it inherited from the parent.
Basic inheritance example
Let's create a simple parent class Animal and then a child class Dog that inherits from it.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "..."
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"
my_dog = Dog("Buddy")
print(my_dog.name)
print(my_dog.speak())Notice how Dog automatically got the name attribute and the __init__ method from Animal. We simply put Animal in parentheses when defining Dog.
Adding attributes in child classes
Child classes can have their own unique attributes. If you want to use the parent's __init__, you should call it explicitly.
class Cat(Animal):
def __init__(self, name, breed):
super().__init__(name) # Call parent's init
self.breed = breed
def speak(self):
return f"{self.name} the {self.breed} says Meow!"
my_cat = Cat("Whiskers", "Siamese")
print(my_cat.name)
print(my_cat.breed)
print(my_cat.speak())The super().__init__(name) line makes sure that the Animal part of the Cat is also initialized correctly before adding breed.
Overriding methods
In our Dog example, we defined a speak method that was different from the Animal's speak method. This is called overriding.
class Bird(Animal):
def speak(self):
return f"{self.name} chirps!"
birdy = Bird("Tweety")
print(birdy.speak())Real-world use case
Think about a graphical user interface (GUI) framework. You might have a base Widget class.
class Widget:
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
def draw(self):
raise NotImplementedError("Subclasses must implement this method")
class Button(Widget):
def __init__(self, x, y, width, height, label):
super().__init__(x, y, width, height)
self.label = label
def draw(self):
return f"Drawing a button at ({self.x},{self.y}) with label: {self.label}"
class TextBox(Widget):
def __init__(self, x, y, width, height, text=""):
super().__init__(x, y, width, height)
self.text = text
def draw(self):
return f"Drawing a text box at ({self.x},{self.y}) with text: '{self.text}'"
button = Button(10, 20, 100, 30, "Click Me")
textbox = TextBox(50, 50, 200, 25, "Enter your name")
print(button.draw())
print(textbox.draw())Here, Button and TextBox inherit common properties from Widget but have their own specific details and drawing instructions.
When to use inheritance
Use inheritance when you have an "is-a" relationship. For example, a Dog IS-A Animal, a Button IS-A Widget.
- When child classes share common functionality with a parent.
- To promote code reuse and reduce duplication.
- To establish a clear hierarchy among related classes.
Common mistakes
It's easy to overuse inheritance, which can make your code harder to understand and maintain.
- Misusing the "is-a" relationship: Don't inherit just to reuse code if the relationship isn't truly "is-a".
- Deep inheritance hierarchies: Too many levels of inheritance can be complex. Keep it simple if possible.
- Not calling
super().__init__: Forgetting this can lead to uninitialized attributes from the parent class.
Practice
Try these exercises to lock in what you just learned.
What's next?
Now that you understand the basics of inheritance, you can explore more advanced topics like multiple inheritance, abstract base classes, and method resolution order. Keep practicing!