Python function advanced

Source: Internet
Author: User
Tags class generator generator iterable

Function Advanced Namespace
    • namespace, as the name implies, is where the names are stored. Example: If you declare a variable x = 1 and the value 1 is stored in memory, the variable name x is stored in the namespace. namespaces are places where x and 1 bindings are stored.

    • There are 3 types of namespaces, respectively:
    • Locals: the namespace within the current function , including local variables and formal parameters
    • GLOBALS: global variable, function definition in the outermost namespace of the module
    • Builtins: Namespaces for built-in modules

    • Scope Range
    • Global scope: Global survival, globally valid
    • Local range: Temporary survival, locally valid

    • LEGB representative name Lookup order: Locals, enclosing function , globals, builtins
      • Locals are namespaces within functions, including local variables and formal parameters
      • enclosing namespaces for outer nested functions
      • Globals global variables, the namespace of the module in which the function is defined
      • Builtins the namespace of the built-in module
Closed Package
    • Preliminary Understanding : Function definitions and function expressions are located in another function body ( nested functions ), the external function returns the function name of the intrinsic function , and the intrinsic function can directly access all the local declarations in the external function where they are located variables, parameters , when such an intrinsic function is called outside of their external function, a closure is formed.

    • definition : The returned function object, not just a function object, also wraps a layer of scope outside the function, which allows the function to be invoked wherever it is called, in addition to the local variables defined inside the function, followed by the scope of its own outer envelope.

def outer():    =‘jack‘    def inner():        print("在inner里打印外层函数的变量", name)    return= outer()   # outer函数执行后等价于 f == innerf()  # inner()
Decorative Device
    • Function: To further enhance the function of functions without changing the code of existing functions
    • Prerequisites: Can form a closure, function as a parameter into the upper function of the namespace, for the internal function to return out of the call
Using the adorner version
    • Simple example:
def f1(func):    def inner():        return func(n)    return inner@f1def f2(x):    print(x)f2()
Detailed Process Analysis
    1. Adding an adorner to the function F2 F2 can be understood as F = F1 (F2), where the right content of the equation is executed first, and the F2 function is stored as a parameter in the namespace of the external function;
    2. F1 returns inner, equivalent to f = inner;
    3. This forms the closure, which calls the F () function outside of the inner function F1, and calls the intrinsic function inner ().
    4. The inner result returns the previously passed parameter function (), i.e. F2()
    5. The inner function then queries the namespace of the external function for the variable or parameter, and finds the previously passed F2 function parameter
    6. Because the previously passed function name is an external function F2 (), the external function is called directly F2 ()
    7. Finally, the function name modification does not affect the function of internal code execution, so directly to the F2, so that is the implementation of the adorner function, without changing the F2 code at the same time, before the start will run F1 (), at this time generate intermediate function Ming variable, function name if it is F2, then the subsequent call F2 () The function F2 () is also activated at the same time.

Example 2: Adding authentication functions to Code

USERNAME= ' Lynnfang 'PASSWORD= ' abc 'Lock_status= 0Login_status= 0defLogin (func,*args):defInner*Args**Kwargs):GlobalLock_status, Login_statusifLock_status== 1:Print(' Your account has been locked! ')Else:ifLogin_status== 0: N= 0                 whileN< 3: username= input(' >>> user name: ') password= input(">>> Password:")ifUsername==USERNAME andPassword==Password:n= 3Login_status= 1                        returnFunc ()Else: N+= 1                Else: Lock_status= 1            Else:returnFunc ()returnInner@logindefChina ():Print('----China zone----')@logindefJapan ():Print('----Japan zone----') China () Japan ()
Code parsing
    1. Without changing the code of the China () and Japan () functions, the user authentication is added, only the authentication pass can call the function inner expression.
    2. The code script is executed first, and Python detects the @ symbol, which will pass the corresponding function name as a parameter to the login () function's namespace
    3. F1 = inner, f2 = inner
    4. Since the invisible intermediate function can be assigned to the previously passed function name, the call to this function name is equivalent to an external call inner
    5. After entering the inner function, after declaring the global variable, the global variable value can be modified inside the nested function, and the value of the global variable will be used as the judging condition of the logical statement inside the nested function, but it will definitely return the previously passed function call ().
    6. Enter the namespace of the login () function to find the corresponding function parameter, since the function parameter is an external function that was previously passed in, it also calls the external function, smoothly into the external execution function inside
    7. As long as you do not exit the program, the next time you enter the login function will refer to the previous global variables to determine the execution, so once logged in, you do not need to repeat the login
Generator (Generator)
    • feature : The generator does not save the results in a series, but instead keeps the generator state, returning a value each time it iterates until the end of the stopiteration exception is encountered.

    • Generator expression : pass-through list parsing syntax, just replace the list parsing [] with ()

    • differences with List resolution : The list of things that the builder expression can do is basically handled, but the list parsing compares the cost of memory when the sequence that needs to be processed is relatively large.

    • A typical generator , g = (i for i in range(1000) G is the generator, and next (g) can iterate over the internal values until the entire generator is emptied

    • Range () in the bottom is implemented with the generator, in Python2, Range (10) Production is the list, so to use Xrange (10), compared to save space, Python3 optimized range (), the result is a class generator, range(121212121212212)‘在python shell下可以马上生成,但是 List (range (121212121212121212)) ' may be slow or even directly due to a memory error, because the list needs to read all the values into memory, but the memory allocated to the list of standard memory is a limited amount of space, so there will be memory errors, this time the generator is a bit of the show

    • The generator is one-time, and an error occurs when the iteration completes StopIteration

Yield understanding
  • The effect of yield is similar to return;
  • When Python recognizes the next () function, it starts executing inside the function until it encounters the yield keyword, and then returns the value of yield to the outside;
  • Each subsequent invocation executes the code backwards from the yield keyword, and then executes from the function head down until it encounters the yield return value until it encounters the next Next ();
  • G.send (' a ') can assign ' a ' to yield
    • The generator implements the range () function
def range2(end):    =0    while< end:        =yield count        +=1= range2(10)print(next(g))print(next(g))print(next(g))g.send(‘stop‘)
    • Make Fabnacci sequence generator by turning function into generator
def fab(max_num):    =001    while< max_num:        yield b  # 把函数执行过程冻结在这一步,并把b的值返回给外面的next(函数)        = b, a+b        +=1= fab(20)print(g)
Iterators
    • Iterative Objects (iterable): objects that can be used for loops are iterative objects, common data sets list, tuple, set, Dict, str are iterative objects

    • Iterator (iterator):
    • The object that can be called by next () and continuously returns the next value is an iterator;
    • Represents a data stream, an ordered sequence
    • Lazy, which is calculated only when the next data needs to be returned
    • Unpredictable size, without Len () this method

    • An iterative object can be converted to an iterator, calling the ITER () function directly

    • To judge an iterative object:isinstance(11, Iterable)

    • Determine if it is an iterator:isinstance((i for i in range(10)), Iterator)

Python function advanced

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.