File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ # coding: utf-8
2+ # file name: decorator.py
3+ # author: wumingming
4+ # description: study of decorator
5+
6+ import time
7+
8+ # function decorator
9+
10+
11+ def self_introduction (func ):
12+ print "I am Bom. "
13+ return func
14+
15+
16+ @self_introduction
17+ def say_hi (name ):
18+ """"""
19+ print "hi, %s" % name
20+
21+
22+ def function_performance_statistics (trace_this = True ):
23+ if trace_this is True :
24+ def performance_statics_delegate (func ):
25+ def counter (* args , ** kwargs ):
26+ start = time .clock ()
27+ print "start time:" , start
28+ func (* args , ** kwargs )
29+ end = time .clock ()
30+ print "end time:" , end
31+ print "used time %d" % (end - start )
32+ return counter
33+ else :
34+ def performance_statics_delegate (func ):
35+ return func
36+
37+ return performance_statics_delegate
38+
39+
40+ @function_performance_statistics (True )
41+ def add (x , y ):
42+ time .sleep (5 )
43+ print "add result: %d" % (x + y )
44+
45+
46+ @function_performance_statistics (False )
47+ def mul (x , y ):
48+ print "mul result:%d" % (x * y )
49+
50+
51+ # class decorator
52+ def bar (dummy ):
53+ print "bar"
54+
55+
56+ def inject (cls ):
57+ cls .bar = bar
58+ return cls
59+
60+
61+ @inject
62+ class Foo (object ):
63+ pass
64+
65+
66+ if __name__ == "__main__" :
67+ # function decorator
68+ print "\n ----------function decorator----------"
69+ say_hi ("tim" )
70+ add (3 , 5 )
71+ mul (3 , 5 )
72+
73+ # class decorator
74+ print "\n -----------class decorator-------------"
75+ foo = Foo ()
76+ foo .bar ()
You can’t perform that action at this time.
0 commit comments