Blog finishing day12

Python day 12

Closure function

Closed (closed function internal functions) package (comprising): a function of an external reference to an internal function rather than global scope scope.

Two kinds of methods as a function of parameter passing

  1. Use parameters

    def func(x):
        print(x)
    
    func(1)
  2. Contracted function

    def func(x):
    #    x = 1
        def f1():
            print(x)
        return f1
    
    f2 = func(2)

Decorator

No reference decorator

What is the decorator

The decorator is a function of nature, decorator is to add additional functionality to be decorative objects

Pay attention to two things:

  • Decorator function object itself can be called any
  • Objects can also be decorated with any function callable objects

Achieve decorator must follow two principles

1. 不修改被装饰对象的源代码
2. 不修改被装饰对象的调用方式

Decorator usage

import time

def index():
    print('welcome to index')
    time.sleep(1)
    
    return 123

def home(name):
    print(f'welcome {name} to page')
    time.sleep(1)
    
    return name

def time_count(func):
    #func = 最原始的index
    def wrapper(*args,**kwargs):
        start = time.time()
        res = func(*args,**kwargs)
        end = time.time()
        print(f'{func} time is {start - end}')
        
        return res
    return wrapper

home = time_count(home)
home('simple')

index = time_count(index)
index()

Decorator syntax sugar

#在被装饰函数上面单独写上@装饰器名
@time_count
# @time_count 就等于 home = time_count(home)
def home(name):
    print(f'welcome {name} to page')
    time.sleep(1)
    
    return name

Decorative template

def deco(func):
    def wrapper(*args,**kwargs):
        res = func(*args,**kwargs)
        return res
    return wrapper

There are parameters decorator

#三层函数
username_list = []

def sanceng(role):
    def login_deco(func):
        def wrapper(*args, **kwargs):
            if username_list:
                print('已经登录,请勿重复登录')
                res = func(*args, **kwargs)
                return res

            username_inp = input('请输入用户名:')
            pwd_inp = input('请输入密码:')

            with open(f'{role}_info.txt', 'r', encoding='utf8') as fr:
                for user_info in fr:
                    username, pwd = user_info.strip().split(':')
                    if username_inp == username and pwd_inp == pwd:
                        print('登录成功')
                        username_list.append(username)
                        res = func(*args, **kwargs)
                        return res
                else:
                    print('登录失败')
        return wrapper
    return login_deco

@sanceng('admin')
def index(x, y):
    print('index')
    print('x,y', x, y)
    return 123

res = index(10, 20)

Guess you like

Origin www.cnblogs.com/samoo/p/11574641.html