时间:2021-07-01 10:21:17 帮助过:31人阅读
原则:1.不能修改被装饰的函数的源代码
2.不能修改被装饰的函数的调用方式
- 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()
注:装饰器得写在被装饰函数的上面。
小实验:密码验证
- 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中关于装饰器的学习的详细内容,更多请关注Gxl网其它相关文章!