无参装饰器:
在调用无参装饰器时,不需要在外层传递参数。
适用于例如:
- 为某个函数增加统计运行时间功能
- 为某个函数运行前增加登录认证功能
有参装饰器:
在调用有参装饰器时,对其传入一个或多个参数。
适用于例如:
- 验证用户类型
def user_auth(user_group):
def wrapper(func):
def inner(*args, **kwargs):
if user_group == 'SVIP':
print('Dear SVIP')
res = func(*args, **kwargs)
return res
elif user_group == 'General':
res = func(*args, **kwargs)
return res
else:
print('Please login first!')
login()
return inner
return wrapper
@user_auth(user_group='SVIP')
def welcome():
print('Welcome to the index')
welcome()