#装饰器
'''
def log(text):
def decorator(func):
def wrapper(*args, **kw):
print('%s %s()' % (text, func.__name__))
return func(*args, **kw)
return wrapper
return decorator
@log('execute')
def now():
print('2015-3-25')
now() #三层嵌套效果是:now = log('execute')(now)
'''
#请设计一个decorator,它可作用于任何函数上,并打印该函数的执行时间:
'''
import functools
import time
def metric(fn):
@functools.wraps(fn)
def wrapper(*args, **kw):
start = time.time()
x = fn(*args, **kw)
print('%s execute in %s ms' % (fn.__name__, (time.time()-start)*1000))
return x
return wrapper
@metric
def fast(x, y):
time.sleep(0.0012)
return x + y;
@metric
def slow(x, y, z):
time.sleep(1.2)
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'的日志。
'''
import functools
import types
def log(obj = None):
text = ""
def decorator(fun):
functools.wraps(fun)
def wrapper(*args, **kw):
print('{0}begin call {1}'.format(text, fun.__name__))
x = fun(*args, **kw)
print('{0}end call {1}'.format(text, fun.__name__))
return x
return wrapper
if isinstance(obj, types.FunctionType) or isinstance(obj, types.BuiltinFunctionType):
return decorator(obj)
elif obj is None:
text = ''
return decorator
else:
text = obj+' '
return decorator
@log('excute')
def fun1():
print('hello world')
@log()
def fun2():
print('hello world')
@log
def fun3():
print('hello world')
fun1()
fun2()
fun3()
'''
这里面有一个小细节希望注意判断一个变量obj是否为函数:
if isinstance(obj, types.FunctionType) or is instance(obj, types.BuiltinFunctionType):
print('obj is function')
types.FunctionType 和 types.BuiltinFunctionType的官方文档解释如下:
types.
FunctionType
types.
LambdaType
The type of user-defined functions and functions created by lambda
expressions.
types.
BuiltinFunctionType
types.
BuiltinMethodType
The type of built-in functions like len()
or sys.exit()
, and methods of built-in classes. (Here, the term “built-in” means “written in C”.)