File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change 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()
You can’t perform that action at this time.
0 commit comments