Home  >  Article  >  Backend Development  >  Learning about decorators in python

Learning about decorators in python

黄舟
黄舟Original
2017-07-27 16:07:301360browse

Definition: It is essentially a function, (decorator other functions) is to add additional functions to other functions

Principles: 1. The source code of the decorated function cannot be modified

2. The calling method of the decorated function cannot be modified

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()

Note: The decorator must be written above the decorated function.

Small experiment: Password verification

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()

The above is the detailed content of Learning about decorators in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn