Class inheritance is an important feature in object-oriented programming (OOP) that allows a new class (known as the “child” or “subclass”) to inherit attributes and methods from an existing class (known as the “parent” or “superclass”).
This provides several important benefits:
Code Reusability: Inheritance allows you to reuse code from an existing class, reducing duplication. The child class can inherit all functionality from the parent class and modify or extend it without rewriting everything from scratch.
Extensibility: Inheritance makes it easy to extend the functionality of an existing class. You can add new features or override methods in the child class to change or enhance behavior.
Maintainability: Centralized logic in a parent class means that changes to the core functionality only need to be made in one place. This simplifies maintenance and reduces the chances of errors when updating code.
Polymorphism: Inheritance supports polymorphism, where child classes can be used interchangeably with their parent classes. This is useful in scenarios where you want different behaviors for different subclasses while maintaining a common interface.
Class Inheritance in Python
Code
class Team():def__init__(self, city, name):self.city = cityself.name = namedef__repr__(self):returnf"<Team '{self.name}'>"def__iter__(self):yield"city", self.cityyield"name", self.name@propertydef full_name(self):returnself.city +" "+self.namedef advertise(self):print("COME TO", self.city.upper(), "TO SEE OUR GAMES!")
In this example, we are creating a BaseballTeam child class that inherits from the Team parent class, while adding in some baseball-specific functionality.
class BaseballTeam(Team):def__init__(self, city, name, short_stop=None, closing_pitcher=None):# ATTRIBUTES SHARED WITH PARENT:super().__init__(city=city, name=name)# CHILD-SPECIFIC ATTRIBUTES:self.short_stop = short_stopself.closing_pitcher = closing_pitcher# OVERRIDING PARENT METHOD:def advertise(self):print("COME TO", self.city.upper(), "TO SEE OUR BASEBALL GAMES, INCLUDING:")print("...", self.short_stop)print("...", self.closing_pitcher)# CHILD-SPECIFIC METHOD:def warm_up_bullpen(self):print("NOW WARMING UP:", self.closing_pitcher)
In this child class, in the initialization method, we invoke super(), which is a reference to the parent class, to initialize an instance of the parent class. Then we initialize some baseball specific parameters (in this case short_stop and closing_pitcher).
Here are some initialization and usage examples for the BaseballTeam child class:
COME TO NEW YORK TO SEE OUR BASEBALL GAMES, INCLUDING:
... Derek Jeter
... Mariano Rivera
Child-specific:
bt.warm_up_bullpen()
NOW WARMING UP: Mariano Rivera
Multiple Inheritance in Python
It is possible to use inheritance to “mix-in” functionality from multiple parent classes:
class Runner:def run(self):return"Runs on the track."class Swimmer:def swim(self):return"Swims in the pool."class Bicyclist:def bike(self):return"Cycles on the road."# INHERITS FROM / "MIXES IN" MULTIPLE PARENTS:class Triathlete(Runner, Swimmer, Bicyclist):pass