import functools
def log(func):
def wrapper(*args,**kw):
print("call %s()"%func.__name__)
return func(*args, **kw)
return wrapper
@log # 在执行处,相当于 now = log(now)
def now():
print("now is now")
# 带参数的装饰器
def log2(text):
def decorator(func):
def wrapper(*args, **kw):
print("%s %s():" % (text,func.__name__))
return func(*args, **kw)
return wrapper
return decorator
@log2("excute")
def now2():
print("now is now")
def log3(func):
@functools.wraps(func) # 用于保留被装饰函数的元信息(如函数名、文档字符串等)
def wrapper(*args, **kw):
print("call %s():"%func.__name__)
return func(*args,**kw)
return wrapper
@ log3
def now3():
print('now3 is now.')
def log4(text):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print('%s %s():'%(text, func.__name__))
return func(*args, **kw)
return wrapper
return decorator
@log4('excute')
def now4():
print('now4 is now.')
if __name__ == '__main__':
# now = log(now)
now()
# now2 = log2('excute')(now2)
now2()
print(now2.__name__)
now3()
print(now3.__name__)
# now4 = log4('excute')(now4)
now4()
print(now4.__name__)
int2 = functools.partial(int,base = 2) # 将二进制数字转换为十进制数字
print(int2('100'))
max2 = functools.partial(max, 10)
# 固定参数,求最大数
print(max2(5, 6, 7)) # 相当于 args = (10,5,6,7)
# max(*args)
输出:
call now()
now is now
excute now2():
now is now
wrapper
call now3():
now3 is now.
now3
excute now4():
now4 is now.
now4
4
10