Skip to content

Commit 2a82040

Browse files
authored
Allow delegator to return delegate's properties
The current code does not allow the delegator to return the value of properties of the delegate but can only call its methods. Moreover if the method does not exist then `None` is returned rather than raising an exception. This PR is for fixing the above.
1 parent ede5733 commit 2a82040

File tree

1 file changed

+18
-7
lines changed

1 file changed

+18
-7
lines changed

fundamental/delegation_pattern.py

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,30 +9,41 @@
99
Allows object composition to achieve the same code reuse as inheritance.
1010
"""
1111

12-
1312
class Delegator(object):
1413
"""
1514
>>> delegator = Delegator(Delegate())
15+
>>> delegator.p1
16+
123
17+
>>> delegator.p2
18+
Traceback (most recent call last):
19+
...
20+
AttributeError: 'Delegate' object has no attribute 'p2'
1621
>>> delegator.do_something("nothing")
1722
'Doing nothing'
1823
>>> delegator.do_anything()
19-
24+
Traceback (most recent call last):
25+
...
26+
AttributeError: 'Delegate' object has no attribute 'do_anything'
2027
"""
2128

2229
def __init__(self, delegate):
2330
self.delegate = delegate
2431

2532
def __getattr__(self, name):
26-
def wrapper(*args, **kwargs):
27-
if hasattr(self.delegate, name):
28-
attr = getattr(self.delegate, name)
29-
if callable(attr):
30-
return attr(*args, **kwargs)
33+
attr = getattr(self.delegate, name)
34+
35+
if not callable(attr):
36+
return attr
3137

38+
def wrapper(*args, **kwargs):
39+
return attr(*args, **kwargs)
3240
return wrapper
3341

3442

3543
class Delegate(object):
44+
def __init__(self):
45+
self.p1 = 123
46+
3647
def do_something(self, something):
3748
return "Doing %s" % something
3849

0 commit comments

Comments
 (0)