day9 (function basics, decorator)

Decorator
a function object:
    Python Everything target
    functions are first-class objects (function may be used as data transfer)
    1 may be referenced i.e. FUNC = X
    2 can be used as the parameters passed to the function.
    3 can be used as the return value of the function
    4 may as the elements of the container data types

Example. 1
    DEF FUNC (X):
        Pass
        return X
    X = FUNC (10) which is called function returns a value other than the function
    X = FUNC
    X ()
    Li = [. 1, X, 2]
Example 2
    DEF FUNC (bar):
        bar ()

    DEF bar ():
        Pass

    FUNC (bar)
Example. 3
    DEF the outter ():
        : DEF Inner ()
            Print ( 'Inner')
        return Inner
    X = the outter ()
    X ()
pyrene function call and define sets
when two function calls to each other
Exceed the maximum depth of recursion error
DEF FUNC ():
    Print ( 'FUNC')
    FUNC ()
DEF bar ():
    Print ( 'bar')
    FUNC ()
FUNC ()
Example 1 nested calls
def max (x, y):
    IF X> Y:
        return X
    the else:
        return Y
DEF MAX4 (X, Y, Z, A):
    RES = max (X, Y)
    RES = max (RES, Z)
    RES = max (RES, Q)
MAX4 (. 1 , 2,3,4,)
Example 2 nested definitions
DEF func1 ():
    DEF func2 ():
        DEF FUNC ():
        Print ( 'AAF')
        FUNC ()
    DEF func2 ()
func1 ()

three namespace scope
3.1
    built-in namespace
    global namespace
    ps: built-in global space variables are global effective >> Search glsbals ()

    Local namespace (function [class] opened runtime memory space
                each partial space independently of one another)
    local namespace can access their outer space

# 2, the scope relations are already fixed in the function definition phase,
    invoking the function regardless of the position,
    the following individuals may not understand
    because when you define a function, correspondence between the function name and the address of the memory will be stored in the current namespace so
    the scope of the relationship is already fixed in the function definition phase. when the function is invoked from the band . namespaces defined called
X =. 1
DEF F1 ():
    DEF F2 ():
        Print (X)
    return F2
X = 100
DEF F3 (FUNC):
    X = 2
    FUNC ()
X = 10000
F3 (F1 () )

# 3, see scope: Globals (), about locals ()

about locals is a namespace within the function, including local variables and parameter
enclosing outer nested namespace function (common closure)
Globals global variables, function definitions where the module's namespace
namespace builtins built-in module
builtins ()
Globals ()
enclosing ()
about locals ()

Four closure function
What is Closures:
 Closures are 1 when calling a function of other built-in functions, built-in functions will give priority to the transfer of its variables within a namespace outer function rather than from the current namespace extracting variables: this is the closure
         2 will function requires data package together, allowing only a specific function (i.e. nested function calls): this is the closure
         essentially similar function by constructing a partial expansion of the inner layer of the external function named space and add a function
     that is based on the concept of function object, you can return to any position to call a function, but the relationship is in the scope of the definition of complete function has been determined, call the location and function nothing to do.    
     That is the function are treated as data processing, always comes with the scope prevail. If the function contains embedded reference to the external scope (not global scope) variables, then the 'nested function' is a function closure referred closures (Closures)
     X =. 1


DEF F1 ():
    DEF F2 ():
        Print (X)

    return F2

DEF f3 ():
    X =. 3
    F2 = f1 () # call to f1 () function returns F2
    F2 () # required to be performed in the role relationship when the function definition, the call regardless of the position

f3 () # results. 1
X =. 1
DEF Outer ():
    X = 2
    DEF Inner ():
        Print (X)
    Inner return

FUNC = Outer ()
FUNC () # 2 results

decorator
what is?
tool other decorative function for
the principle of
a decorative function without changing the source code
2 does not change the way calls are decorated function
decorator:
    no arguments decoration control:
writing:
the first step
def outer (func): (name of the incoming decorative function)
    DEF Inner (* args, ** kwargs):
    return Inner
part II
def outer (func): (incoming decorated function name)
    DEF Inner (* args, ** kwargs):
        Print ( 'code block. 1')
        RES = FUNC (* args, ** kwargs)
        Print ( 'block 2')
        return RES
    return Inner
third portion
@outer
FUNC DEF ():
    Pass


decorator function (draft)
Import Time
# DEF the Login (File):
#     inp_name = input('place input your username !').strip()
#     inp_password = input('place input yuor password').strip()
#     with open(file, mode='r', encoding='utf-8') as f:
#         date = []
#         for line in f:
#             iofo = line.strip().split()
#             date.append(iofo)
#             if inp_name == iofo[0].strip() and inp_password == iofo[1]:
#                 return True
#         return False
#
# print(login(file=f'user_iofo'))

def outter(func):
    def inner(*args, **kwargs):
        start = time.time()
        login(*args, **kwargs)
        end = time.time()
        print(end-start)
    Inner return


@outter
DEF Login (File):
    inp_name = INPUT ( 'INPUT Place your username!') Strip ().
    inp_password = INPUT ( 'INPUT Place for yuor password') Strip ().
    with Open (File, MODE = 'R & lt ', encoding =' UTF-. 8 ') AS F:
        DATE = []
        for F in Line:
            . iofo = line.strip () Split ()
            date.append (iofo)
            IF inp_name == iofo [0] .strip ( ) and inp_password == iofo [. 1]:
                return True
        return False
'' 'should not return to True' '' # because now returns the inner login value
Print (login (File = f'user_iofo '))
Print ( True)

improvements completed, there were drawbacks.
    1 does not return a value corresponding change
    2 no corresponding change textual interpretation
decorator improved (sub draft)

# Import Time
# def outter(func):
#     
#     def inner(*args, **kwargs):
#          inner.__doc__=login.__doc__
#          inner.__name__=login.__name__
#         start = time.time()
#         res = login(*args, **kwargs)
#         end = time.time()
#         print(end-start)
#         return res
#     return inner
#
#
# @outter
# def login(file):
#     inp_name = input('place input your username !').strip()
#     inp_password = input('place input yuor password').strip()
#     with open(file, mode='r', encoding='utf-8') as f:
#         date = []
#         for line in f:
#             iofo = line.strip().split()
Date.append # (iofo)
# == IF inp_name iofo [0] .strip () == iofo and inp_password [. 1]:
# return True
# return False
# '' 'should not returns True' ''
# Print ( the Login (File = f'user_iofo '))
# Print (True)

# change the name of a text document trickier> so we call tool to modify
from functools Wraps Import
Import Time
DEF the outter (FUNC):
    @wraps (FUNC)
    DEF Inner (* args , ** kwargs):
        Start the time.time = ()
        RES = FUNC (* args, ** kwargs)
        End = the time.time ()
        Print (Start-End)
        return RES
    return Inner


@outter
DEF Login (File):
    inp_name = input ( 'place input your username !').strip()
    inp_password = INPUT ( 'Place INPUT for yuor password') Strip ().
    with Open (File, MODE = 'R & lt', encoding = 'UTF-. 8') AS F:
        DATE = []
        for Line in F:
            iofo = Line. . Strip () Split ()
            date.append (iofo)
            IF inp_name == iofo [0] .strip () == iofo and inp_password [. 1]:
                return True
        return False
'' 'should not return to True' ''
Print (the Login (File = f'user_iofo '))
Print (True)
Print (Help (the Login))
there is a reference decorator
    inner functions need to pass additional parameters, while the outer and inner function function could not pass other parameters.
    so we that add a layer of closure to pass parameters
first step
DEF ginseng (the X-, the y-):
    DEF Outer (FUNC):
        Pass
    return Outer ()
Step
def ginseng(x,y):
    def outer(func):
        def inner():
            pass
        return inner
    return outer()
第三步
def ginseng(x,y):
    def outer(func):
        def inner(*args,**kwargs):
            print(x,y)
            set =func(*args,**kwargs)
            return set
    return inner

def ginseng(x,y):
    def outer(func):
        def inner(*args,**kwargs):
            print(x,y)
            set =func(*args,**kwargs)
            return set
        return inner
    return outer

Personal understanding decorator
    with no arguments decorator: function is used to expand the function, add additional features to the original function
    Principle 1 source does not move the same way calling 2
    (1) it is necessary to add new features while keeping the original function code unchanged == >> then only to re-write a function (with outer function as an example) the original function of the incoming outer function,
        and then add new features to expand in the outer function function (call nested functions)
    (2) but it requires a call the same way, is called a good solution (method can be used to copy), but make sure to call the new function name and the original function of mass participation consistent and be passed to the original function.
        the outer function parameters passed include the original function, not may be associated with the same parameters as the original function, we can only write again a function
        (for example with inner function) the original function of the parameters passed in inner functions, and make it consistent with the parameters of the original function (defined nested functions)
    (3 ) because we [must ensure that we pass the original function can be called the incoming parameters] so only write a function again in the outer or the inner function, but also because we have to know the original function parameters passed in
        what is, so the outer function in the outermost Incoming layer (function name), a second inner layer function, receiving parameters of the original function mode, and the parameters passed to the original function (using (* args, ** kwargs)) is
    added to the inner functions to the function (4) within the function, is responsible for receiving the inner parameters of the original function, that we use the inner function instead of the original function, so you want to add functionality. inside the function
    (5) Finally, the outer () returns the inner, then outer () assigned to the function name of the original function. Example login = outer () = inner. call login () call is equivalent to inner () function is completed so far out

Guess you like

Origin www.cnblogs.com/lee1225/p/12466961.html