Extending Functionality Through Subclassing
In this lesson, you will learn how to make your code more powerful by adding unique features to a child class without losing the foundation built in the parent class.
When we create a derived class (a subclass), it automatically gains all the methods and attributes of the base class. However, the real power of subclassing lies in extending that base functionality. You aren’t limited to what the parent provides; you can add entirely new methods and attributes that are specific to the new, more specialized object.
Adding New Capabilities
Think of a base Vehicle class that handles basic movement. A Car subclass might inherit those movement methods, but you can add an open_trunk() method that only makes sense for a car, not for every generic vehicle.
Here is how you define new attributes and methods in a subclass:
class Vehicle:
def __init__(self, brand):
self.brand = brand
def drive(self):
return f"The {self.brand} is moving."
class Car(Vehicle):
def __init__(self, brand, trunk_size):
# Use the parent's logic to set up the brand
super().__init__(brand)
# Add a new attribute specific to Car
self.trunk_size = trunk_size
# Add a brand new method
def open_trunk(self):
return f"Opening trunk with capacity: {self.trunk_size} liters."
my_car = Car("Toyota", 450)
print(my_car.drive()) # Inherited from Vehicle
print(my_car.open_trunk()) # New functionality in Car
In the example above, Car extends Vehicle by adding trunk_size as a specialized attribute and open_trunk() as a specialized behavior. The super() call allows us to leverage the base class initialization while ensuring our subclass can track extra information. By doing this, you keep your code DRY (Don't Repeat Yourself) while ensuring your specialized objects can do everything they need to do in your specific application.
Key Takeaway: Subclassing allows you to inherit a foundation from a base class and then introduce new, specialized attributes and methods to handle unique requirements.