Junior — Middle
What is the role and application of mixins in Python for extending class functionality?
sobes.tech AI
Answer from AI
Mixins in Python are classes that provide additional functionality to other classes through multiple inheritance, without being standalone entities. They allow extending class behavior without the need to create a deep inheritance hierarchy.
Role of mixins:
- Adding specific methods or properties to classes.
- Reusing code across different classes.
- Separating functionality into independent components.
Example of using a mixin to add logging:
class LoggerMixin:
def log(self, message):
print(f"LOG: {message}")
class DataProcessor(LoggerMixin):
def process(self, data):
self.log(f"Processing data: {data}")
# data processing
processor = DataProcessor()
processor.process("sample data")
In this example, the LoggerMixin class adds a log method, which becomes available in DataProcessor. This allows extending functionality without changing the core logic of the class.