Delegation in Python

Delegation is a design pattern in object-oriented programming that allows an object to hand off (delegate) a task to another object. In Python, delegation can be implemented to achieve composition, where an object maintains a reference to another object and delegates method calls to that referenced object. This promotes code reuse and separation of concerns, allowing for cleaner and more maintainable code.

Characteristics of Delegation

Example of Delegation

This example demonstrates how to use delegation in Python to perform tasks using separate classes.

Code Example

class Printer:
            def print_document(self, document):
                print("Printing:", document)
        
        class Scanner:
            def scan_document(self):
                return "Scanned Document"
        
        class MultiFunctionDevice:
            def __init__(self):
                self.printer = Printer()  # Delegation to Printer
                self.scanner = Scanner()  # Delegation to Scanner
        
            def print(self, document):
                self.printer.print_document(document)
        
            def scan(self):
                return self.scanner.scan_document()
        
        # Using the MultiFunctionDevice
        mfd = MultiFunctionDevice()
        mfd.print("My Document.txt")
        scanned_doc = mfd.scan()
        print("Received:", scanned_doc)

Output

Printing: My Document.txt
Received: Scanned Document

Conclusion

Delegation is a powerful technique in Python that enhances the design of classes by promoting composition and separation of concerns. By delegating tasks to specialized objects, developers can create more maintainable and reusable code, leading to improved software architecture.