|
1 | 1 | #!/usr/bin/env python
|
2 |
| -"""https://docs.python.org/2/library/functools.html#functools.wraps""" |
3 |
| -"""https://stackoverflow.com/questions/739654/how-can-i-make-a-chain-of-function-decorators-in-python/739665#739665""" |
| 2 | +""" |
| 3 | +Reference: https://en.wikipedia.org/wiki/Decorator_pattern |
| 4 | +""" |
4 | 5 |
|
5 |
| -from functools import wraps |
6 | 6 |
|
| 7 | +class TextTag(object): |
| 8 | + """Represents a base text tag""" |
| 9 | + def __init__(self, text): |
| 10 | + self._text = text |
7 | 11 |
|
8 |
| -def makebold(fn): |
9 |
| - return getwrapped(fn, "b") |
| 12 | + def render(self): |
| 13 | + return self._text |
10 | 14 |
|
11 | 15 |
|
12 |
| -def makeitalic(fn): |
13 |
| - return getwrapped(fn, "i") |
| 16 | +class BoldWrapper(object): |
| 17 | + """Wraps a tag in <b>""" |
| 18 | + def __init__(self, wrapped): |
| 19 | + self._wrapped = wrapped |
14 | 20 |
|
| 21 | + def render(self): |
| 22 | + return "<b>{}</b>".format(self._wrapped.render()) |
15 | 23 |
|
16 |
| -def getwrapped(fn, tag): |
17 |
| - @wraps(fn) |
18 |
| - def wrapped(): |
19 |
| - return "<%s>%s</%s>" % (tag, fn(), tag) |
20 |
| - return wrapped |
21 | 24 |
|
| 25 | +class ItalicWrapper(object): |
| 26 | + """Wraps a tag in <i>""" |
| 27 | + def __init__(self, wrapped): |
| 28 | + self._wrapped = wrapped |
22 | 29 |
|
23 |
| -@makebold |
24 |
| -@makeitalic |
25 |
| -def hello(): |
26 |
| - """a decorated hello world""" |
27 |
| - return "hello world" |
| 30 | + def render(self): |
| 31 | + return "<i>{}</i>".format(self._wrapped.render()) |
28 | 32 |
|
29 | 33 | if __name__ == '__main__':
|
30 |
| - print('result:{} name:{} doc:{}'.format(hello(), hello.__name__, hello.__doc__)) |
| 34 | + simple_hello = TextTag("hello, world!") |
| 35 | + special_hello = ItalicWrapper(BoldWrapper(simple_hello)) |
| 36 | + print("before:", simple_hello.render()) |
| 37 | + print("after:", special_hello.render()) |
31 | 38 |
|
32 | 39 | ### OUTPUT ###
|
33 |
| -# result:<b><i>hello world</i></b> name:hello doc:a decorated hello world |
| 40 | +# before: hello, world! |
| 41 | +# after: <i><b>hello, world!</b></i> |
0 commit comments