ⅩⅥ: Job

A: preparation of function (the time function performed by time.sleep (n) analog)

import time
def du():
    print("嘟嘟喂嘟嘟")
    time.sleep(2)

Two: write a decorator, as a function of time together with statistical functions

import time
def run_time(func):
    def inner(*args, **kwargs):
        start = time.time()
        func(*args, **kwargs)
        stop = time.time()
        print('run func\'s time is', stop-start)
    return inner

@run_time
def index(*args, **kwargs):
    time.sleep(1)
    print('welcome index')
index()

Three: write a decorator, as a function of plus certified function

import time
def inner(func):
    inp_user = input('your name:').strip()
    inp_pwd = input('your password:').strip()
    def file():
        with open(r'db.txt', 'rt', encoding='utf-8') as f:
            for line in f:
                line = line.strip()
                user_dic = eval(line)
                if inp_user == user_dic['name']:
                    if inp_pwd == user_dic['password']:
                        print('login successful')
                        func(inp_user)
                        break
                    else:
                        print('password err')
                        break
            else:
                print('user is not find')
    return file

@inner
def index(name):
    time.sleep(1)
    print('welcome 【%s】' % name)
index()

Four: write a decorator for multiple functions plus certified function (from the user's account password file) require a login is successful, the follow-up functions are no longer need to enter a user name and password

Note: read a file from the string dictionary can be used eval ( '{ "name": "egon", "password": "123"}') turn into a dictionary format

Five: write a decorator for several functions plus authentication, requires a successful login, without having to repeat the login within the timeout period, exceeding the timeout, you must log in again

Six: Optional Problem

# 思考题(选做),叠加多个装饰器,加载顺序与运行顺序,可以将上述实现的装饰器叠加起来自己验证一下
# @deco1 # index=deco1(deco2.wrapper的内存地址)
# @deco2 # deco2.wrapper的内存地址=deco2(deco3.wrapper的内存地址)
# @deco3 # deco3.wrapper的内存地址=deco3(index)
# def index():
#     pass

Guess you like

Origin www.cnblogs.com/qujiu/p/12555348.html