-
Notifications
You must be signed in to change notification settings - Fork 2
/
magic_methods.py
61 lines (49 loc) · 1.36 KB
/
magic_methods.py
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
58
59
60
61
__doc__ = """Magic methods
"""
import doctest
class Talker(object):
"""
>>> talker = Talker()
>>> talker.say("Hello!")
'Hello!'
>>> talker.scream("Hey!")
'Hey!'
>>> talker.whine("I want candy!")
'I want candy!'
>>> talker = Talker()
>>> talker.whistle("La-la-la!")
Traceback (most recent call last):
...
AttributeError: I know only how to say, scream or whine!
"""
def _do_action(self, phrase):
return phrase
def __getattr__(self, item):
if item in ('say', 'scream', 'whine'):
return self._do_action
raise AttributeError("I know only how to say, scream or whine!")
class Meta(type):
def _do_action(cls, phrase):
return phrase
def __getattr__(cls, item):
if item in ('say', 'scream', 'whine'):
return cls._do_action
raise AttributeError("I know only how to say, scream or whine!")
class CTalker(object):
"""
>>> talker = CTalker
>>> talker.say("Hello!")
'Hello!'
>>> talker.scream("Hey!")
'Hey!'
>>> talker.whine("I want candy!")
'I want candy!'
>>> talker = Talker()
>>> talker.whistle("La-la-la!")
Traceback (most recent call last):
...
AttributeError: I know only how to say, scream or whine!
"""
__metaclass__ = Meta
if __name__ == "__main__":
doctest.testmod()