python 3.x learning note 5 (decorator)

Keywords: Python

1. Decorator:

Function in essence, which is to add additional functions to other functions


1) the source code of the decorated function cannot be modified
2) the call mode of the decorated function cannot be modified

2. Realize the knowledge reserve of decorators:

1) function is "variable"

2) higher order function

A. pass a function as an argument to another function (you can add functions without modifying the source code of the decorated function)

b. the return value contains the function name) (the calling method of the function is not modified)

3) nested function

3. Higher order function + nested function = decorator


4. Preliminary decorator

import time
def timer(func):              #timer(test1)  func = test1
    def deco():
        start_time = time.time()
        func()                #run test1
        stop_time = time.time()
        print('the func run time is %s'%(stop_time-start_time))
    return deco

@timer              #test1 = timer(test1)
def test1():
    print('in the test1')

5. Decorative devices with perfect functions


user,passwd = 'hsj','1234'

def auth(auth_type):
    print('auth func:',auth_type)
    def outer_wrapper(func):
        def wrapper(*args, **kwargs):
            print('wrapper:',*args, **kwargs)
            if auth_type == 'local':
                username = input('Username:').strip()
                password = input('Password:').strip()

                if username == user and password == passwd:
                    print('\033[32;1mUser has pass authentication\033[0m')
                    return func(*args, **kwargs)  # from home         #Return value of function wrapper
                    exit('\033[31;1mInvalid username or password\033[0m')
            elif auth_type =='ldap':
        return wrapper
    return outer_wrapper

def index():
    print('welcome to index psge')
@auth(auth_type='local')      # Parenthesized is equivalent to running outer_wraper So I will execute the contents   # home = auth(home)
def home():
    print('welcome to home page')
    return 'from home'         #There is a return value in the decorator. Otherwise, print () can't come out
def bbs():
    print('welcome to bbs page')


Posted by jpopuk on Sat, 02 May 2020 07:48:51 -0700