Superclass in Python
A superclass in Python is a fundamental concept in object-oriented programming. It serves as a base class from which other classes, known as subclasses, inherit attributes and methods. This mechanism allows for code reuse, reduces duplication, and promotes a hierarchical organization of code. By defining common functionality in a superclass, subclasses can automatically inherit these features, simplifying code structure and maintenance.
Overview
A superclass provides a set of attributes and methods that can be reused or specialized by its subclasses. This relationship is often described as an 'is-a' relationship, where the subclass is a specialized version of the superclass. For example, if Frame is a superclass, a CarbonFiberFrame subclass would be a specialized type of Frame.
Creating a Superclass
Creating a superclass involves identifying shared attributes and methods among potential subclasses and defining them in a single class. This approach centralizes shared functionality, making the codebase more manageable and easier to update.
Example Structure
Below is a basic structure of a superclass Employee and a subclass Supervisor. The Supervisor class inherits all non-private attributes and methods from the Employee class:
class Employee:
def __init__(self, name, employee_id):
self.name = name
self.employee_id = employee_id
def login(self):
print(f"An employee {self.name} just logged in.")
def logout(self):
print(f"An employee {self.name} just logged out.")
class Supervisor(Employee):
pass
In this example, the Supervisor class inherits the login and logout methods from the Employee class without needing to redefine them.
Inheritance and Method Resolution Order (MRO)
When a subclass inherits from a superclass, it automatically gains access to the superclass's attributes and methods. This inheritance allows subclasses to use these features without redefining them. However, if a subclass needs to provide a specific implementation for a method, it can override the superclass's method completely or partially.
Complete and Partial Overriding
- Complete Overriding: A subclass can completely override a method from the superclass by providing a new implementation, effectively replacing the superclass's method.
- Partial Overriding: A subclass can extend the functionality of a superclass's method by calling the superclass's method using
super()and then adding additional behavior.
Method Resolution Order (MRO)
The MRO determines the order in which methods and attributes are resolved in a class hierarchy. It starts with the subclass, moves to the superclass, and finally to the object class if necessary. This order is crucial in ensuring that the correct method implementations are used when a method is called on an instance.
Figure 8.10 MRO in a hierarchical class structure.
Costs of Creating Hierarchical Structures
While creating a hierarchical class structure can be beneficial, it also introduces tight coupling between subclasses and the superclass. This coupling can complicate maintenance, as changes in a subclass may necessitate updates in the superclass, potentially affecting other subclasses.
Example with Data Classes
In data classes, when creating a subclass, all fields from the superclass are inherited by the subclass. For example:
@dataclass
class BaseBill:
meal_amount: float
@dataclass
class TippedBill(BaseBill):
tip_amount: float
In this example, the TippedBill class inherits the meal_amount field from the BaseBill class, demonstrating how data classes can also utilize inheritance to share attributes.
Using super()
The super() function in Python is a powerful tool that allows subclasses to access and extend the behavior of their superclasses. This is particularly useful when a subclass needs to override a method but still wants to retain the original behavior provided by the superclass.
Example: Using super()
class Teller:
def deposit(self, amount, account):
account.deposit(amount)
class CorruptTeller(Teller): #1
def __init__(self):
self.coffers = 0
def deposit(self, amount, account): #2
self.coffers += amount * 0.01 #3
super().deposit(amount * 0.99, account) #4
#1 A corrupt teller is-a teller.
#2 The corrupt teller overrides the default deposit behavior.
#3 The corrupt teller skims a little off the top for himself.
#4 He deposits the rest the way any teller does, but using a different amount.
In this example, CorruptTeller is a subclass of Teller. It overrides the deposit method to skim a small percentage of the deposit amount for itself. However, it still uses the super().deposit() call to perform the actual deposit operation, demonstrating how a subclass can extend and modify the behavior of its superclass.
Visual Representation
Figure 8.9 Creating a superclass that handles the shared attributes and methods.
| Book Title | Usage of superclass | Technical Depth | Connections to Other Concepts | Examples Used | Practical Application |
|------------|---------------------|-----------------|-------------------------------|---------------|-----------------------|
| [Python How-To](https://www.manning.com/books/python-how-to) | Discusses superclass as a foundational class for inheritance, emphasizing code reuse and structure. [more](https://livebook.manning.com/book/python-how-to/chapter-8/264) | Covers method resolution order (MRO) and the costs of hierarchical structures. [more](https://livebook.manning.com/book/python-how-to/chapter-8/294) | Connects to concepts like MRO, complete and partial overriding, and data classes. [more](https://livebook.manning.com/book/python-how-to/chapter-8/290) | Provides examples with `Employee` and `Supervisor` classes, and data classes. [more](https://livebook.manning.com/book/python-how-to/chapter-8/282) | Highlights practical issues like tight coupling in hierarchical structures. [more](https://livebook.manning.com/book/python-how-to/chapter-8/320) |
| [Practices of the Python Pro](https://www.manning.com/books/practices-of-the-python-pro) | Defines superclass as a base class for code reuse and organization, focusing on the 'is-a' relationship. [more](https://livebook.manning.com/book/practices-of-the-python-pro/chapter-8/25) | Explains the use of `super()` for accessing and extending superclass behavior. [more](https://livebook.manning.com/book/practices-of-the-python-pro/chapter-8/88) | Emphasizes the 'is-a' relationship and proper use of inheritance. [more](https://livebook.manning.com/book/practices-of-the-python-pro/chapter-8/56) | Uses examples like `Frame` and `Tire` classes, and `CorruptTeller` subclass. [more](https://livebook.manning.com/book/practices-of-the-python-pro/chapter-8/90) | Demonstrates practical subclass behavior and the use of `super()` in real-world scenarios. [more](https://livebook.manning.com/book/practices-of-the-python-pro/chapter-8/90) |
FAQ (Frequently asked questions)
What is a superclass in Python?
Why is a superclass used in programming?
What do subclasses inherit from a superclass by default?
How do you handle shared attributes and methods in object-oriented programming?
What is the basic structure of a superclass and subclass in Python?
How does a subclass inherit methods from a superclass in Python?
How do you create a superclass in Python?
What is the benefit of creating a superclass?
What is a bottom-up approach in creating a superclass?
How do subclasses use attributes and methods from a superclass?
What does complete overriding mean in a superclass context?
What is the MRO in a superclass context?
How does the MRO affect method resolution in Python classes?
What is a potential downside of creating a hierarchical class structure?
What is partial overriding in a superclass context?
How do data classes handle inheritance in Python?
What is the ideal use case for inheritance?
What is a superclass in object-oriented programming?
Can you give examples of superclasses and subclasses?
Why should subclasses use all the behavior of their superclasses?
What role does a superclass play in Python?
How can you access superclass behavior in Python?