23day
装饰器:
1、用户不执行前不调用函数,在调用的时候再执行函数
a、传函数时不加参数
user_status = False # 用户登录了就把这个改成True def login(func): def inner(): _username = ‘alex‘ _password = ‘abc123‘ global user_status if user_status == False: username = input("user:") password = input("password:") if username == _username and password == _password: print("welcome login...") user_status = True else: print("wrong username or password!") if user_status: func() return inner @login def home1(): print("首页1") @login #等值于 home2 = login(home2) def home2(): print("首页2") @login def home3(): print("首页3") home1() home2() home3()
b、传函数时增加参数:
注:可以使用非固定函数*args、**kwargs。当传参数给函数时,取参数。不给函数传参数,则不取
1 user_status = False # 用户登录了就把这个改成True 2 def login(func): 3 def inner(*args,**kwargs): 4 _username = ‘alex‘ 5 _password = ‘abc123‘ 6 global user_status 7 if user_status == False: 8 username = input("user:") 9 password = input("password:") 10 if username == _username and password == _password: 11 print("welcome login...") 12 user_status = True 13 else: 14 print("wrong username or password!") 15 16 if user_status: 17 func(*args,**kwargs) 18 return inner 19 @login 20 def home1(): 21 print("首页1") 22 # @login #等值于 home2 = login(home2) 23 def home2(n): 24 print("首页2",n) 25 26 def home3(): 27 print("首页3") 28 home1() 29 home2(‘3p‘) 30 home3()
c、带参数的装饰器
可在外函数与内函数之间再套一层过度函数
user_status = False # 用户登录了就把这个改成True def login(func): def outer(func): def inner(*args,**kwargs): _username = ‘alex‘ _password = ‘abc123‘ global user_status if user_status == False: username = input("user:") password = input("password:") if username == _username and password == _password: print("welcome login...") user_status = True else: print("wrong username or password!") if user_status: func(*args,**kwargs) return inner return outer @login(‘qq‘) #先执行login(‘qq‘) 再将login(‘qq‘)@到home1 def home1(): print("首页1") # @login #等值于 home2 = login(home2) def home2(n): print("首页2",n) def home3(): print("首页3") home1() home2(‘3p‘) home3()