Extend base-class behavior by defining a subclass.
How It Works
Inheritance lets a child class reuse or override behavior from a parent class. The child inherits available attributes and methods; use composition instead when the relationship is not truly an is-a relationship.
issubclass() can help inspect class relationships.
Step-by-Step Example
class Notification:
def message(self):
return "General notification"
class EmailNotification(Notification):
def message(self):
return "Email notification"
print(EmailNotification().message())
Understanding the Example
- The class groups related state and methods so each instance can manage its own values.
- The function definition gives the operation a reusable name and makes its inputs explicit.
A successful run of this example prints the following output:
Email notification
Where This Fits in a Real Program
A class is useful when data and the operations that preserve its rules belong together. Distinguish class-level attributes from per-instance state, and make invalid operations fail clearly. Inheritance is not always needed: simpler composition or a standalone function may be easier to maintain.
Practice: Try It Yourself
Add an SMSNotification subclass with a specialized message.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Assuming child classes automatically override methods without defining the same name.
- Using inheritance only for code sharing when the domain relationship is not meaningful.
Key Takeaways
- Extend base-class behavior by defining a subclass.
- Inheritance lets a child class reuse or override behavior from a parent class.
- issubclass() can help inspect class relationships.