详解Python装饰器
1.定义
本质是函数,用来装饰其他函数,为其他函数添加附加功能
2.原则
a.不能修改被装饰函数的源代码
b.不能修改被装饰的函数的调用方式
3.实现装饰器知识储备
a.函数就是变量
b.高阶函数
i.把一个函数当作实参传给另外一个函数,在不修改被装饰函数源代码情况下为其添加功能
ii.返回值中包含函数名,不修改函数的调用方式
c.嵌套函数
高阶函数+嵌套函数==》装饰器
#Author:Lockegogo
user,passwd='LK','130914'
defauth(auth_type):
print('authfunc:',auth_type)
defouther_wrapper(func):
defwrapper(*args,**kwargs):
print('wrapperfunc:',*args,**kwargs)
ifauth_type=='local':
username=input('username:').strip()
password=input('password:').strip()
ifuser==usernameandpassword==passwd:
print('\033[32;1mUserhaspassedauthentication\033[0m')
res=func(*args,**kwargs)
returnres
else:
exit('\033[32;1mInvalidUsernameorpassword\033[0m')
elifauth_type=='ldap':
print('ldap,不会')
returnwrapper
returnouther_wrapper
defindex():
print('welcometoindexpage')
@auth(auth_type='local')#home=outher_wrapper(home)
defhome():
print('welcometohomepage')
return'fromhome'
@auth(auth_type='ldap')
defbbs():
print('welcometobbspage')
index()
print(home())
bbs()
Decorator
以上所述是小编给大家介绍的Python装饰器详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!