Multiple Inheritance and Mixins
Python supports multiple inheritance, which allows a class to inherit from more than one parent class. Multiple inheritance is when a class inherits from more than one base class.
Mixins are a design pattern that provides a way to reuse code across multiple classes without the need for multiple inheritance. Mixins are a type of class that provide specific functionality to other classes but are not intended to be used as standalone classes.
Example:
class A:
def method_a(self):
print("Method A")
class B:
def method_b(self):
print("Method B")
class C(A, B):
pass
c = C()
c.method_a() # Output: Method A
c.method_b() # Output: Method B
Composition and Aggregation
Composition and aggregation are two techniques for building complex objects from simpler ones. Composition implies a strong relationship between the parts and the whole, while aggregation implies a weaker relationship.
Example:
class Engine:
def start(self):
print("Engine started")
class Car:
def __init__(self):
self.engine = Engine()
def start(self):
self.engine.start()
car = Car()
car.start() # Output: Engine started
Design Patterns
Design patterns are reusable solutions to common problems in software design. Some popular design patterns in Python include the singleton, factory, and observer patterns.
Example:
# Singleton pattern
class Singleton:
_instance = None
@classmethod
def instance(cls):
if not cls._instance:
cls._instance = cls()
return cls._instance
singleton1 = Singleton.instance()
singleton2 = Singleton.instance()
print(singleton1 is singleton2) # Output: True
Hands-on Exercises
- Implement a mixin class for logging messages to a file.
- Create a class hierarchy for a zoo using composition and inheritance.
- Implement the observer pattern to notify subscribers when an event occurs.
Real-World Example
Advanced object-oriented programming concepts are widely used in large-scale software systems to improve code organization, maintainability, and reusability.
Additional Resources
- Python documentation: https://docs.python.org/3/tutorial/classes.html
- Real Python: https://realpython.com/python3-object-oriented-programming/
- W3Schools Python tutorial: https://www.w3schools.com/python/python_classes.asp
Review Questions
- Explain the difference between multiple inheritance and mixins in Python.
- What are the key differences between composition and aggregation?
- Describe the singleton design pattern and provide an example of its use in Python.
Summary and Next Steps
In this lesson, you have learned about:
- Multiple inheritance and mixins
- Composition and aggregation
- Design patterns
In the next lesson, you will learn about multithreading and concurrency in Python, which will help you build more efficient and responsive programs.
Remember to review the material periodically and practice your skills to reinforce your learning. Good luck on your journey to becoming a Python developer!



