这里以写一个auth认证功能装饰器为例,理解装饰器实现原理:
因为装饰器是一个函数,定义一个auth函数
def auth(func): def inner(*args, **kwargs): username = input('username:').strip() password = input('password:').strip() if username == 'admin' and password == 'admin': print('Authentication sucess!') func(*args, **kwargs) else: print('Authentication failed!') return inner @auth # demo = auth(demo) --> demo = inner def demo(n): # 被装饰的函数demo print('function demo %s is running..'%n) demo(1) # 相当于inner(1)
以上,实现了无参数的装饰器
有参装饰器:
def auth(auth_type, *args, **kwargs): # 三层就够了,因为所有参数都可以在最外层传进来
def auth2(func): def inner(*args, **kwargs): username = input('username:').strip() password = input('password:').strip()
if auth_type == 'file': # 以下应该是从文件读取出用户数据 if username == 'admin' and password == 'admin': print('Authentication sucess!') func(*args, **kwargs) else: print('Authentication failed!')
else: # 可以拓展mysql/oracle等不同类型数据库的读取数据方法
print('auth_type invalid!') return inner
return auth2 @auth(auth_type='file') # demo = auth2(demo) --> demo = inner def demo(n): # 被装饰的函数demo print('function demo %s is running..'%n) demo(1) # 相当于auth(1) --> inner(1)
以上,实现了有参装饰器