Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit aedcee1

Browse files
committed
better decorator example
1 parent ca9e299 commit aedcee1

File tree

1 file changed

+19
-49
lines changed

1 file changed

+19
-49
lines changed

decorator.py

+19-49
Original file line numberDiff line numberDiff line change
@@ -1,55 +1,25 @@
1-
#!/usr/bin/env python
2-
# -*- coding: utf-8 -*-
1+
'''https://docs.python.org/2/library/functools.html#functools.wraps'''
2+
'''https://stackoverflow.com/questions/739654/how-can-i-make-a-chain-of-function-decorators-in-python/739665#739665'''
33

4-
"""http://stackoverflow.com/questions/3118929/implementing-the-decorator-pattern-in-python"""
4+
from functools import wraps
55

6+
def makebold(fn):
7+
@wraps(fn)
8+
def wrapped():
9+
return "<b>" + fn() + "</b>"
10+
return wrapped
611

7-
class foo_decorator(object):
12+
def makeitalic(fn):
13+
@wraps(fn)
14+
def wrapped():
15+
return "<i>" + fn() + "</i>"
16+
return wrapped
817

9-
def __init__(self, decoratee):
10-
self._decoratee = decoratee
11-
12-
def f1(self):
13-
print("decorated f1")
14-
self._decoratee.f1()
15-
16-
def __getattr__(self, name):
17-
return getattr(self._decoratee, name)
18-
19-
20-
class undecorated_foo(object):
21-
22-
def f1(self):
23-
print("original f1")
24-
25-
def f2(self):
26-
print("original f2")
27-
28-
29-
@foo_decorator
30-
class decorated_foo(object):
31-
32-
def f1(self):
33-
print("original f1")
34-
35-
def f2(self):
36-
print("original f2")
37-
38-
39-
def main():
40-
u = undecorated_foo()
41-
v = foo_decorator(u)
42-
# The @foo_decorator syntax is just shorthand for calling
43-
# foo_decorator on the decorated object right after its
44-
# declaration.
45-
46-
v.f1()
47-
v.f2()
18+
@makebold
19+
@makeitalic
20+
def hello():
21+
'''a decorated hello world'''
22+
return "hello world"
4823

4924
if __name__ == '__main__':
50-
main()
51-
52-
### OUTPUT ###
53-
# decorated f1
54-
# original f1
55-
# original f2
25+
print('result:{} name:{} doc:{}'.format(hello(), hello.__name__, hello.__doc__))

0 commit comments

Comments
 (0)