* Closure function decorator

Closure function

  • Closure means: a function of an internal function of the external reference, and not scope of global scope.

  • Two kinds of transmission parameters as a function of ways: in the form of parameters; packet function

def f1(x):
    def f2():
        print(x)
    return f2
    
f = f1(5)  # f-->f2,x=5
f()  # f()-->f2(),x=5  # 5
f()  # 5


f3 = f1(3)  # f-->f2,x=3
f3()  # f()-->f2(),x=3  # 3
f3()  # 3
  • The internal variables defined into internal function, so that the two go together return
  • Break the hierarchy, the local variables get used globally, and can be packaged into an external variable x f2, and then next time will be able to directly call f2
  • Application: delay calculation (mass participation turns out that we are now wrapped), reptiles fields.

Decorator

1. What is a decorator?

Decorator refers to add additional functionality to the decorator object. Thus the definition is to define a decorator function, but the function of the function is used for other functions having a decorative function.

have to be aware of is:

  • Decorator itself can actually be any object that can be called
  • Ornamented objects can be any callable objects
2. Why use a decorator?

If we have a project on line, we need to modify a particular method, but we do not want to modify the method of use, this time you can use decorator. Because the software maintenance should follow the open closed principle that once the software on-line operation, maintenance and modification of software source code is closed, the extended function refers to the open.

Achieve decorator must follow two principles:

  1. Does not modify the source code of an object to be decorated
  2. Call does not modify the manner of decorative objects

Decorator in fact, add new features to the object to be decorated under the premise of following the above two principles.

  • Decorator: change the function of the time does not change the original invocation, and change the code of the original function
to sum up:
  • Call decorator and passed as a parameter to sleep

  • Interior decorator only a defined function and return function, so the calling function will not be executed when the wrapper function returns only the name wrapper

  • Using the concept of function object is assigned to the original decorative function name, equivalent to assign the name to the original wrapper function name

  • The original name of the function + () implementation of the time equivalent to calling interior decorators wrapper function

  • Variable elongate wrapper function parameters participant receives all incoming and an outer decorative function assigned to the inner layer, if the incoming original name of a function, the innermost layer can directly call the original function

  • Function innermost layer is called directly instead of an assignment, so the code runs directly

  • Within the wrapper function can add functionality as needed, while the innermost function (original function) can be assigned to a variable, the value returned in the wrapper, you can make use of the function of the outer layer


def deco(func):
    def wrapper(*args,**kwargs):  # 赋值后的time_sleep
        res = func(*args,**kwargs)  # 真正的time_sleep
        
        return res
    return wrapper

@deco  # time_sleep(赋值后的) = deco(time_sleep(真正的))
def time_sleep(name):
    print(name)
    return 123

No reference decorator

is_login_dict = {'username': None}


def login_deco(func):
    
    def wrapper(*args, **kwargs):  # 赋值后的time_sleep

        if not is_login_dict['username']:

            username = input('请输入你的用户名》》》').strip()

            if username != 'fanping':
                print('非法登录')

                return

            is_login_dict['username'] = username

            res = func(*args, **kwargs)  # 真正的time_sleep

            return res
        else:
            res = func(*args, **kwargs)  # 真正的time_sleep

            return res         

    return wrapper


@login_deco
def shopping():
    print('from shopping')


@login_deco
def withdraw():
    print('from withdraw')

There are parameters decorator

is_login_dict = {'username': None}

def auth(origin):
    
    def login_deco(func):

        def wrapper(*args, **kwargs):  # 赋值后的time_sleep

            if origin == 'file':

                if not is_login_dict['username']:

                    username = input('请输入你的用户名》》》').strip()

                    if username != 'fanping':
                        print('非法登录')

                        return

                    is_login_dict['username'] = username

                    res = func(*args, **kwargs)  # 真正的time_sleep

                    return res
                else:
                    res = func(*args, **kwargs)  # 真正的time_sleep

                    return res

            elif origin == 'mongodb':
                print('非法登录')
                
            else:
                print('dsb')


        return wrapper
    
    return login_deco


# f = origin('file')  # login_deco
# shopping = f(shopping)
# shopping()


@auth('file')
def shopping():
    print('from shopping')


@auth('mongodb')
def withdraw():
    print('from withdraw')

Guess you like

Origin www.cnblogs.com/gongjingyun123--/p/10957086.html