-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecorator.py
More file actions
131 lines (95 loc) · 2.75 KB
/
decorator.py
File metadata and controls
131 lines (95 loc) · 2.75 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# coding: utf-8
# file name: decorator.py
# python version: 2.7
# author: wu ming ming
# description: study of decorator
import time
import sys
import functools
# function decorator
def self_introduction(func):
print sys._getframe().f_lineno, "I am Bom. "
return func
@self_introduction
def say_hi(name):
""""""
print sys._getframe().f_lineno, "hi, %s" % name
def function_performance_statistics(trace_this=True):
if trace_this is True:
def performance_statics_delegate(func):
def counter(*args, **kwargs):
start = time.clock()
print sys._getframe().f_lineno, "start time:", start
func(*args, **kwargs)
end = time.clock()
print sys._getframe().f_lineno, "end time:", end
print sys._getframe().f_lineno, "used time %d" % (end - start)
return counter
else:
def performance_statics_delegate(func):
return func
return performance_statics_delegate
@function_performance_statistics(True)
def add(x, y):
time.sleep(2)
print sys._getframe().f_lineno, "add result: %d" % (x + y)
@function_performance_statistics(False)
def mul(x, y):
print sys._getframe().f_lineno, "mul result:%d" % (x * y)
# class decorator
def bar(dummy):
print sys._getframe().f_lineno, "bar"
def inject(cls):
cls.bar = bar
return cls
@inject
class Foo(object):
pass
class Human(object):
def __init__(self, func):
self.name = None
self.func = func
def __call__(self, *args, **kwargs):
self.eat()
return self.func
@staticmethod
def breath():
print sys._getframe().f_lineno, "I need air"
def eat(self):
print sys._getframe().f_lineno, "I am %s, I want rice" % self.name
@Human
def someone():
pass
def CatDecorator(cls):
@functools.wraps(cls)
class new_class:
def __init__(self, name):
cls.__init__(self, name)
self.sex = "male"
def set_sex(self, sex):
self.sex = sex
def get_set(self):
return self.sex
return new_class
@CatDecorator
class Cat(object):
def __init__(self, name):
self.name = name
if __name__ == "__main__":
# function decorator
print "\n----------function decorator----------"
say_hi("tim")
add(3, 5)
mul(3, 5)
# class decorator
print "\n-----------class decorator-------------"
foo = Foo()
foo.bar()
Human.breath()
Tim = Human("Tim")
Tim.breath()
Tim.eat()
Bob = someone()
Jack = Cat("Jack")
Jack.set_sex("femal")
print Jack.get_set()