Mastering Inheritance: Base and Derived Classes
In this lesson, you will learn how to create a "parent-child" relationship between classes, allowing one class to automatically acquire the features of another.
The Power of Inheritance
Inheritance is a core principle of Object-Oriented Programming that allows you to define a Base Class (the parent) that contains common logic, and a Derived Class (the child) that inherits those traits while adding its own unique functionality. This prevents code duplication—instead of rewriting methods, the derived class simply "borrows" them.
Creating the Relationship
To define a derived class, you place the name of the base class in parentheses immediately following the derived class name in the class definition.
Consider a system for a library. We might have a generic Item and a more specific Book.
# The Base Class
class Item:
def __init__(self, title):
self.title = title
def display(self):
print(f"Item: {self.title}")
# The Derived Class
class Book(Item):
def __init__(self, title, author):
# We inherit 'title' logic from Item
super().__init__(title)
self.author = author
# We add unique behavior here
def display_details(self):
print(f"Book: {self.title} by {self.author}")
# Using the derived class
my_book = Book("The Great Gatsby", "F. Scott Fitzgerald")
my_book.display() # Borrowed from Item
my_book.display_details() # Defined in Book
In the example above, Book is the Derived Class and Item is the Base Class. By using super().__init__(title), we ensure the Book successfully sets up the attributes defined in the base Item class, while the Book instance gains access to both its own methods and the methods of its parent.
This structure allows you to build complex hierarchies where specific objects share a common foundation, making your code significantly easier to maintain and extend as your application grows.
Key Takeaway: Inheritance allows a derived class to inherit attributes and methods from a base class, promoting code reuse and establishing clear, logical relationships between your data structures.