Introduction
Inheritance is a key concept in Python's Object-Oriented Programming (OOP) paradigm. It allows you to create new classes based on existing classes, inheriting their attributes and methods. In this guide, we'll explore the fundamentals of inheritance in Python and demonstrate how to extend classes with sample code.
What Is Inheritance?
Inheritance is the mechanism by which a new class (subclass or derived class) is created by inheriting attributes and methods from an existing class (base class or superclass). This promotes code reusability and hierarchical structuring of classes.
Defining a Base Class
To create a base class, you define a class with attributes and methods that can be shared by other classes. Here's an example of a simple "Vehicle" base class:
# Defining a base class
class Vehicle:
def __init__(self, make, model):
self.make = make
self.model = model
def start(self):
return f"Starting the {self.make} {self.model}"
Extending a Class
To create a subclass that inherits from a base class, you define a new class with the name of the base class in parentheses. The subclass can add additional attributes and methods or override existing ones.
# Extending a class (creating a subclass)
class Car(Vehicle):
def __init__(self, make, model, year):
super().__init__(make, model)
self.year = year
def honk(self):
return "Honk! Honk!"
# Overriding a method
def start(self):
return f"Starting the {self.year} {self.make} {self.model}"
Creating Objects of Subclasses
You can create objects of the subclass and use the attributes and methods inherited from the base class as well as those defined in the subclass.
# Creating objects of the subclass
my_car = Car("Toyota", "Camry", 2022)
# Using attributes and methods
print(my_car.make) # Output: "Toyota"
print(my_car.honk()) # Output: "Honk! Honk!"
print(my_car.start()) # Output: "Starting the 2022 Toyota Camry"
Conclusion
Inheritance is a powerful tool in Python's Object-Oriented Programming that allows you to create and organize classes hierarchically. It promotes code reusability and simplifies the modeling of real-world concepts by building upon existing classes. Understanding inheritance is crucial for effective Python programming.