Skip to content

Commit 1745105

Browse files
authored
Python之装饰器
Python之装饰器
1 parent 762a8ed commit 1745105

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

studynotes/Python之装饰器.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,3 +114,41 @@
114114

115115
if __name__ == '__main__':
116116
foo('aaa')
117+
## 三、带参数的装饰器
118+
**对于带参数的装饰器,需要多一层嵌套关系。比如,实现一个装饰器,控制"被装饰函数"的执行次数。**
119+
120+
def repeat(num):
121+
def actual_deco(func):
122+
def deco(*args, **kwargs):
123+
for _ in range(num):
124+
print('执行第%d次' % num)
125+
func(*args, **kwargs)
126+
return deco
127+
return actual_deco
128+
129+
@repeat(num=3)
130+
def foo(arg):
131+
print('in the foo! ', arg)
132+
133+
if __name__ == '__main__':
134+
foo('aaa')
135+
## 四、类装饰器
136+
**类装饰器必须实现__call__()方法**
137+
138+
class count_time:
139+
def __init__(self, func):
140+
self.func = func
141+
142+
def __call__(self, *args, **kwargs):
143+
start_time = time.time()
144+
self.func()
145+
end_time = time.time()
146+
print('run time is ', end_time - start_time)
147+
148+
@count_time
149+
def foo():
150+
time.sleep(2)
151+
print('in the foo!')
152+
153+
if __name__ == '__main__':
154+
foo()

0 commit comments

Comments
 (0)