装饰器的进阶
-
有参装饰器:
# def warpper(func): # def inner(*args,**kwargs): # user = input("user:") # pwd = input("pwd:") # if user == 'alex' and pwd == "dsb": # func(*args,**kwargs) # return inner # # @warpper # def foo(): # print("被装饰的函数") # # foo()
博客园和码云切换登陆
# def auth(argv): # def warpper(func): # def inner(*args,**kwargs): # if argv == "博客园": # print("欢迎登录博客园") # user = input("user:") # pwd = input("pwd:") # if user == 'alex' and pwd == "dsb": # func(*args,**kwargs) # elif argv == "码云": # print("欢迎登录码云") # user = input("user:") # pwd = input("pwd:") # if user == 'alex' and pwd == "jsdsb": # func(*args, **kwargs) # # return inner # return warpper # # def foo(): # print("被装饰的函数") # # msg = input("请输入您要登录的名字:") # a = auth(msg) # foo = a(foo) # foo()
def auth(x): def auth2(func): def inner(*args, **kwargs): if login_status['status']: ret = func() return ret if x == 'wechat': username = input('请输入用户名:').strip() password = input('请输入密码:').strip() if username == '太白' and password == '123': login_status['status'] = True ret = func() return ret elif x == 'qq': username = input('请输入用户名:').strip() password = input('请输入密码:').strip() if username == '太白' and password == '123': login_status['status'] = True ret = func() return ret return inner return auth2 @auth('wechat') def jitter(): print('记录美好生活') @auth('qq') def pipefish(): print('期待你的内涵神评论') 解题思路: @auth('wechat') :分两步: 第一步先执行auth('wechat')函数,得到返回值auth2 第二步@与auth2结合,形成装饰器@auth2 然后在依次执行。
-
多个装饰器装饰一个函数规则:先执行离被装饰函数最近的装饰器
def wrapper1(func): def inner1(*args,**kwargs): print("这是装饰器一开始") func(*args,**kwargs) print("这是装饰器一结束") return inner1 def wrapper2(func): def inner2(*args,**kwargs): print("这是装饰器二开始") func(*args,**kwargs) print("这是装饰器二结束") return inner2 @wrapper1 @wrapper2 def func(): print("这是被装饰的函数") func() 打印结果: 这是装饰器一开始 这是装饰器二开始 这是被装饰的函数 这是装饰器二结束 这是装饰器一结束
def auth(func): # wrapper1装饰器里的 inner def inner(*args,**kwargs): print("额外增加了一道 锅包肉") func(*args,**kwargs) print("锅包肉 38元") return inner def wrapper1(func): # warpper2装饰器里的 inner def inner(*args,**kwargs): print("额外增加了一道 日魔刺生") func(*args,**kwargs) print("日魔刺生 白吃") return inner def wrapper2(func): # 被装饰的函数foo def inner(*args,**kwargs): print("额外增加了一道 麻辣三哥") func(*args,**kwargs) print("难以下嘴") return inner @auth # 1 7 @wrapper1 # 2 6 @wrapper2 # 3 5 def foo(): # 4 print("这是一个元宝虾饭店") 小技巧:按v字执行 语法糖拆解: foo = wrapper2(foo) # inner = wrapper2(foo) foo = wrapper1(foo) # inner = wrapper1(inner) foo = auth(foo) # inner = auth(inner) foo() # auth里边的inner()
顺序流程图: