Day 12 function closure decorator

Closure function

Review:
1. function object: You can define functions within the function's return to the global level function using thus breaking the limit.
2. The namespace and scope: the scope of the definition phase relationship when the function has been fixed dead, and calls find time regardless of the position, that is calling the function in any position need to go to define the scope of a function
definition: function closure is actually inside the function, and the function of internal references to external variables rather than the scope of the global scope, closure means: internal reference function outside the scope function instead of the global scope

  • Two kinds of transmission parameters as a function of the embodiment
    1. The parameters used in the form of
    2 contracted functions: packet function is a function of two nested together.
  • Application package closure function
    meaning closure: the function returns an object, not just a function object, outside the scope function also wrapped in a layer, which makes the function regardless of where the call is preferentially used their outer the scope of the package.

Application: delay calculation (turns out that we are mass participation, and now we are wrapped up), reptiles fields.

Decorator

1. What is the decorator
if there is a function, we have no basis to modify this function up to expand its functionality, this time used a decorator, the decorator worth is added to the decorator object additional functionality, thus defining decorator is the definition of a function, but the function of the function is used to add extra functionality to the other function

  • Decorator itself can actually be any object that can be called
  • Ornamented objects can be any callable objects

2. Why use a decorator
because, if we already have a project on the line, we want to modify a method, but this method may be used in many places, change bad prone to problems, so, this time with decoration is it ,, without changing the method can also be extended on other functions, and does not affect the original method call.
implement the decorator must follow two principles:
1. does not modify the source code of the object to be decorated
2. does not modify the way decorative objects is called
so, decorator is in fact the premise is to follow the above two principles are adding new features decorative objects

3. decorator syntactic sugar
is directly above in the decorative function, and is written on a separate line @装饰器名
4. The decoration template

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

5 have reference decorator

6. Closure Layer

Guess you like

Origin www.cnblogs.com/bladecheng/p/10957015.html