python 3.7 练习
- 设计一个decorator,它可作用于任何函数上,并打印该函数的执行时间:
def metric(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
begin = time.time()
result = fn(*args, **kwargs)
end = time.time()
print('%s executed in %s ms' % (fn.__name__, (end - begin) * 1000))
return wrapper
# 测试
@metric
def fast(x, y):
time.sleep(0.0012)
return x + y
@metric
def slow(x, y, z):
time.sleep(0.1234)
return x * y * z
f = fast(11, 22)
s = slow(11, 22, 33)
if f != 33:
print('测试失败!')
elif s != 7986:
print('测试失败!')
- 编写一个decorator,能在函数调用的前后打印出'begin call'和'end call'的日志:
def log(x):
def decorator(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
print('%s %s():' % (text, fn.__name__))
fn(*args, **kwargs)
return wrapper
if isinstance(x, str):
text = x + ' '
return decorator # 若log传了str参数x,则给text赋值,并调用decorator将fn传递给decorator
else:
text = ''
return decorator(x) # 若x不是str,也就代表传递的是方法本身,则给text一个默认值,再调用decorator(x)
@log
def f():
pass
f()
print(f.__name__)
@log('execute')
def f():
pass
f()
print(f.__name__)
有点费脑子get✔