# 导包绑定函数名
import functools
# 外层为装饰器,内层的闭包函数为具体扩展功能的函数
def output(fun):
@functools.wraps(fun) # 绑定原函数名,需要引入functools
def wrapper(*args, **kwargs):
print('正在调用output')
return fun(*args, **kwargs)
return wrapper
# 带参装饰器
def with_k(str):
def output(fun):
@functools.wraps(fun) # 绑定原函数名,需要引入functools
def wrapper(*args, **kwargs):
print(str)
return fun(*args, **kwargs)
return wrapper
return output
# 定义装饰器判断数据类型
def adjust(fun):
@functools.wraps(fun)
def wrapper(*args, **kwargs):
or_true = True # 默认为非数字
for item in args:
if not isinstance(item, int) and not isinstance(item, float):
or_true = False
break
for key, value in kwargs.items():
if not isinstance(value, int) and not isinstance(value, float):
or_true = False
break
print('正在执行adjust')
if or_true:
return fun(*args, **kwargs) # 符合条件,返回原函数
else:
return ValueError('Type is wrong!')
return wrapper
@with_k('带参装饰器')
@output
@adjust
def sum_two(num1, num2):
return num1+num2
print(sum_two(1, 8))
print(sum_two(num1=1, num2=8))
print(sum_two.__name__)
网友评论