本文摘自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中lambda函数的用法介绍(附示例)
适合利用Python合并多个装饰器?
Python使用cx_oracle模块操作oracle数据库详解
学Python安装什么软件
Python 查找字符在字符串中的位置实例
Python中常见字符串方法推荐
Python中type()是什么意思
学Python需要英语基础吗
Python中+=连用是什么意思
Python爬虫对dota排行榜爬取的实例
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » python中关于装饰器的学习