Home > Backend Development > Python Tutorial > Learning about decorators in python

Learning about decorators in python

黄舟
Release: 2017-07-27 16:07:30
Original
1430 people have browsed it

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()
Copy after login

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()
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template