Inheritance is a fundamental concept in object-oriented programming that enables you to create a class that inherits attributes and methods from another class. This allows for code reusability and a hierarchical class structure.
Defining a Parent Class
In Python, any class can serve as a parent class. To define a parent class, use the standard class creation syntax:
class Book: def __init__(self, title, genre): self.title = title self.genre = genre def display_info(self): print(f"{self.title} is a {self.genre} book.")
In this example, the Book
class has two properties: title
and genre
, and a method display_info
to print these properties.
Creating a Child Class
To create a child class that inherits from the Book
class, specify the parent class in parentheses:
class Fiction(Book): pass
The Fiction
class now inherits all properties and methods from the Book
class without adding any new features, as indicated by the pass
statement.
To verify, create an object of the Fiction
class and call the display_info
method:
my_book = Fiction("1984", "Dystopian") my_book.display_info() # Expected output: 1984 is a Dystopian book.
Enhancing the Child Class with __init__()
To add custom initialization to the child class, define an __init__()
method in the child class. This method will override the parent’s __init__()
method:
class Fiction(Book): def __init__(self, title, subgenre): super().__init__(title, "Fiction") self.subgenre = subgenre
The super()
function is used to call the parent’s __init__()
method, ensuring that the title
property is set correctly while adding the new subgenre
property to the Fiction
class.
Adding New Methods
Child classes can also have their own methods. For instance, you might want to add a method to the Fiction
class to provide additional functionality:
class Fiction(Book): def __init__(self, title, subgenre): super().__init__(title, "Fiction") self.subgenre = subgenre def describe(self): print(f"{self.title} is a {self.subgenre} fiction book.")
Here, the describe
method is unique to the Fiction
class. This demonstrates how inheritance allows child classes to extend or override parent class functionalities.
my_book = Fiction("The Hobbit", "Fantasy") my_book.display_info() # Expected output: The Hobbit is a Fiction book. my_book.describe() # Expected output: The Hobbit is a Fantasy fiction book.
Inheritance in Practice
When working with inheritance, it’s essential to understand how to properly use the super()
function to maintain the relationship between parent and child classes. The child’s __init__()
method can override the parent’s, but by using super()
, you ensure that all necessary initialization from the parent class is still performed.
Exercise
What is the correct keyword to use inside an empty class to avoid an error?
- empty
- inherit
- pass