本文摘自php中文网,作者黄舟,侵删。
定义:本质上就是个函数,(装饰器其他函数)就是为了给其他函数添加附加功能原则:1.不能修改被装饰的函数的源代码
2.不能修改被装饰的函数的调用方式
1 2 3 4 5 6 7 8 9 10 11 12 13 | import time
def timer(hello):
def func( * args, * * kwargs):
start = time.time()
hello( * args, * * kwargs)
end = time.time()
print ( "运行时间:%s" % (end - start))
return func
@timer
def hello():
time.sleep( 2 )
print ( "nihao" )
hello()
|
注:装饰器得写在被装饰函数的上面。
小实验:密码验证
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | import time
user = {
"luozeng" : '123' ,
"xuemanfei" : '456' ,
"xutian" : '789'
}
def yanzheng(hello):
def func( * args, * * kwargs):
start = time.time()
username = input ( "请输入用户:" ).strip()
password = input ( "请输入密码:" ).strip()
if username in user and password = = user[username]:
print ( "登陆成功" )
hello( * args, * * kwargs)
else :
exit( "用户名或密码错误!" )
end = time.time()
print ( "运行时间:%s" % (end - start))
return func
@yanzheng
def hello():
print ( "你好!" )
hello()
|
以上就是python中关于装饰器的学习的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
用Python画红色五角星的代码是什么
Python range函数怎么用
Python基础之输入输出和运算符
Python中socket实现tcp通信的介绍(附示例)
Python介绍嵌套 json 秒变 dataframe!
中谷教育Python视频教程资源推荐
Python3.6想使用urllib2包怎么办
怎么用cmd运行Python
Python换行符怎么用?
__init__ 在 Python 中的用法
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » python中关于装饰器的学习