Uh oh!
There was an error while loading. Please reload this page.
forked from faif/python-patterns
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdelegation_pattern.py
More file actions
Latest commit
57 lines (41 loc) · 1.25 KB
/
Copy pathdelegation_pattern.py
File metadata and controls
57 lines (41 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
"""
Reference: https://en.wikipedia.org/wiki/Delegation_pattern
Author: https://github.com/IuryAlves
*TL;DR
Allows object composition to achieve the same code reuse as inheritance.
"""
from __future__ importannotations
fromtypingimportAny, Callable, Union
classDelegator:
"""
>>> delegator = Delegator(Delegate())
>>> delegator.p1
123
>>> delegator.p2
Traceback (most recent call last):
...
AttributeError: 'Delegate' object has no attribute 'p2'
>>> delegator.do_something("nothing")
'Doing nothing'
>>> delegator.do_anything()
Traceback (most recent call last):
...
AttributeError: 'Delegate' object has no attribute 'do_anything'
"""
def__init__(self, delegate: Delegate):
self.delegate=delegate
def__getattr__(self, name: str) ->Union[Any, Callable]:
attr=getattr(self.delegate, name)
ifnotcallable(attr):
returnattr
defwrapper(*args, **kwargs):
returnattr(*args, **kwargs)
returnwrapper
classDelegate:
def__init__(self):
self.p1=123
defdo_something(self, something: str) ->str:
returnf"Doing {something}"
if__name__=="__main__":
importdoctest
doctest.testmod()