Advanced Method Patterns
Decorator-Enhanced Methods
Method Decorators
def log_method_call(func):
def wrapper(*args, **kwargs):
print(f"Calling method: {func.__name__}")
return func(*args, **kwargs)
return wrapper
class DataProcessor:
@log_method_call
def process_data(self, data):
return [x * 2 for x in data]
Method Resolution Strategies
graph TD
A[Method Resolution] --> B[Single Inheritance]
A --> C[Multiple Inheritance]
A --> D[Method Overriding]
A --> E[Super() Calls]
Inheritance and Method Overriding
class BaseModel:
def validate(self, data):
return len(data) > 0
class UserModel(BaseModel):
def validate(self, data):
base_validation = super().validate(data)
return base_validation and isinstance(data, dict)
Special Method Patterns
Special Method |
Purpose |
Example |
__call__ |
Make instances callable |
Function-like objects |
__getattr__ |
Dynamic attribute handling |
Proxy objects |
__repr__ |
Object string representation |
Debugging |
Callable Instances
class Multiplier:
def __init__(self, factor):
self.factor = factor
def __call__(self, x):
return x * self.factor
double = Multiplier(2)
print(double(5)) ## Outputs: 10
Context Management Methods
class ResourceManager:
def __enter__(self):
print("Entering context")
return self
def __exit__(self, exc_type, exc_value, traceback):
print("Exiting context")
with ResourceManager() as rm:
print("Inside context")
Method Caching and Optimization
from functools import lru_cache
class MemoizedCalculator:
@lru_cache(maxsize=128)
def fibonacci(self, n):
if n < 2:
return n
return self.fibonacci(n-1) + self.fibonacci(n-2)
LabEx Pro Tip
Advanced method patterns require deep understanding of Python's object-oriented programming principles. Experiment and practice to master these techniques.
- Use decorators judiciously
- Understand method resolution order
- Leverage built-in Python optimizations
- Profile your code for performance bottlenecks