PHP前端开发

python中关于装饰器的学习

百变鹏仔 8小时前 #Python
文章标签 python

定义:本质上就是个函数,(装饰器其他函数)就是为了给其他函数添加附加功能

原则:1.不能修改被装饰的函数的源代码

           2.不能修改被装饰的函数的调用方式

import timedef timer(hello):    def func(*args,**kwargs):    #函数传参,不限个数。        start = time.time()        hello(*args,**kwargs)    #函数传参,不限个数。        end = time.time()        print("运行时间:%s"%(end - start))    return func@timerdef hello():    time.sleep(2)    print("nihao")hello()

注:装饰器得写在被装饰函数的上面。

 小实验:密码验证

立即学习“Python免费学习笔记(深入)”;

import timeuser = {                           #存储用户名和密码    "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@yanzhengdef hello():    print("你好!")hello()