装饰器

基本装饰器

1
2
3
4
5
6
7
8
9
10
import time
def timer(func):
start_time = time.time()
end_time = time.time()
func()
print(end_time-start_time)

@timer
def foo():
print('foo')

被装饰函数带参数

1
2
3
4
5
6
7
8
9
10
11
12
import time
def timer(func):
def inner(*args, **kwargs):
start_time = time.time()
end_time = time.time()
func(*args, **kwargs)
print(end_time-start_time)
return inner

@timer
def run(name, age):
print('running', name)

装饰器函数带参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import time
def timer(user_message):
print(user_message)
def outer(func):
def inner(*args, **kwargs):
start_time = time.time()
end_time = time.time()
func(*args, **kwargs)
print(end_time-start_time)
return inner
return outer
@timer("user_message")
def run(name, age):
print('running', name)

被装饰函数带返回值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import time
def timer(user_message):
print(user_message)
def outer(func):
def inner(*args, **kwargs):
start_time = time.time()
end_time = time.time()
temp = func(*args, **kwargs)
print(end_time-start_time)
return temp
return inner
return outer
@timer("user_message")
def run(name, age):
print('running', name)

print(run('name', 'age'))