-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path9.1.py
More file actions
41 lines (31 loc) · 892 Bytes
/
9.1.py
File metadata and controls
41 lines (31 loc) · 892 Bytes
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
# -*- coding: utf-8 -*-
"""
9.1.py
~~~~~~
给函数添加一个包装
1. 元编程: 用美妙的函数或类来处理重复性的代码和工作
"""
import time
from functools import wraps # 导入装饰器模块
def time_func(func):
"""一个装饰器,添加计算函数执行时间的功能"""
@wraps(func)
def wrapper(*args, **kwargs):
"""wrapper 被修饰函数"""
start = time.time()
end = time.time()
print ("The time of %s : %d") % (func.__name__, end - start)
return func(*args, **kwargs)
return wrapper
@time_func # @语法糖
def test(n):
"""测试函数"""
while n > 0 :
n -= 1
# 使用这个装饰器1
test(1000000)
# 使用这个装饰器2
test = time_func(test)
test(1000000) # 为什么会有两个输出? 难道是个 bug ?
print test.__name__
print test.__doc__