Python function advanced

Source: Internet
Author: User
Tags closure wrapper

Wedge

If there is a function, the implementation returns a larger value in two numbers:

def my_max (x, y):    m = x if x>y else y    return m
Bigger = My_max (10,20)
Print (bigger)

Before I told you to return the results back, did you do it? But have you ever wondered why we should return the results? If we do not return m, print directly in the program, OK?

To see the results:

>>> def my_max (x, y): ...     m = x if x>y else y ... >>> my_max (10,20) >>> print (m) Traceback (most recent call last):  File "< Stdin> ", line 1, in <module>nameerror:name ' m ' are not defined

The error! The error is "name ' m ' isn't defined". Variable m is not defined ... Why? I clearly defined it!

Here we begin by remembering how the Python code runs when it encounters a function.

After the Python interpreter starts executing, it opens up a space in memory

Whenever a variable is encountered, the corresponding relationship between the variable name and the value is recorded.

But when a function definition is encountered, the interpreter simply reads the function name into memory , indicating that the function exists, and that the variables inside the function and the logic interpreter do not care at all.

When executing to a function call, the Python interpreter will open up a memory to store the contents of the function , at which point the variables in the function are stored in the newly opened memory. The variables in the function can only be used inside the function, and all the contents of this memory will be emptied as the function executes.

We give a name to the space that "holds the relationship between names and values"-called namespaces

At the beginning of the code, the space created to store the "variable name-value relationship" is called the global namespace , and the temporary space opened in the function's run is called the local namespace .

Back to Top

Namespaces and Scopes

The nature of namespaces: the binding relationship between names and values

The Zen of Python

As mentioned in the Zen of Python: Namespaces are a great idea, let's use it to the fullest!

The namespaces are divided into three types:

Global namespaces

Local namespaces

Built-in namespaces

* The built-in namespace holds the Python interpreter's name for us: Input,print,str,list,tuple ... They are all familiar to us and can be used in a way.

Order of loading and taking values between three namespaces:

Load order: Built-in namespaces (pre-Program load)-Global namespaces (program run: Load from top to bottom) local namespaces (program run: Load only when called)

Value:

Built-in namespaces, local namespaces, and global namespaces, local call spaces

x = 1def F (x):    print (x) print (10)

Global invocation: Built-in namespaces, global namespaces

x = 1def F (x):    print (x) f (Ten) print (x)
Print (max)

Scope

Scope is the scope of action, according to the effective scope can be divided into global scope and local scope.

Global scope: Contains built-in namespaces, global namespaces , can be referenced anywhere throughout the file, are globally valid

Local scope: Local namespace, only valid locally

Globals and Locals methods

Print (Globals ()) print (Locals ())
def func ():    a =    b = Print (    locals ()) Print (    globals ()) func ()

Global keyword

A = 10def func ():    global a    = 20print (a) func () print (a)

Back to Top

Nested and scoped chains of functions

Nested calls to functions

def max2 (x, y):    m  = x if x>y else y    return mdef max4 (a,b,c,d):    res1 = Max2 (A, b)    res2 = Max2 (res 1,C)    Res3 = Max2 (res2,d)    return res3# max4 (23,-7,31,11)

Nested Definitions of functions

Def f1 ():    print ("in F1")    def f2 ():        print ("in F2")    F2 () F1 ()
Def f1 ():    def f2 ():        def f3 ():            print ("In-F3") Print ("In-        F2")        F3 ()    print ("in F1")    F2 ()    F1 ()

Scope chain of a function

Def f1 ():    a = 1    def f2 ():        print (a)    F2 () F1 ()
Def f1 ():    a = 1    def f2 ():        def f3 ():            print (a)        F3 ()    F2 () F1 ()
Def f1 ():    a = 1    def f2 ():        a = 2    f2 ()    print (' A in F1: ', a) F1 ()

nonlocal keywords

# 1. External must have this variable
# 2. Variables with the same name can no longer appear before an intrinsic function declares a nonlocal variable
# 3. Internally modify this variable if you want to take effect in the first layer function that has this variable externally
Def f1 ():    a = 1    def f2 ():        nonlocal a        a = 2    f2 ()    print (' A in F1: ', a) F1 ()

Back to Top

The nature of function names

The function name is essentially the memory address of the function.

1. Can be referenced

def func ():    print (' in Func ') F = funcprint (f)

2. Elements that can be used as container types

Def f1 ():    print (' F1 ') def f2 (): Print (    ' F2 ') def f3 ():    print (' F3 ') L = [f1,f2,f3]d = {' F1 ': F1, ' F2 ': F2, ' F3 ' : f3} #调用l [0] () d[' F2 '] ()

3. Can be used as a function parameter and return value

* Don't you understand? Just remember a word, just use it as a normal variable.

The first class of objects (first-class object) refers to 1. You can create 2 at run time. Use as a function parameter or return value 3. The entity that can be stored in a variable.
Back to Top

Closed Package

def func ():    name = ' Eva '    def Inner ():        print (name)

Closure function:

An intrinsic function contains a reference to an outer scope rather than a full-action domain name, which is called a closure function
#函数内部定义的函数称为内部函数

Because of the scope of the relationship, we cannot get the variables and functions inside the function. What if we just want to take it? Come back!

We all know the variables inside the function. If we want to use it outside the function, we can return the variable directly, so what if we want to call the function inside the function outside?

Would it be nice to return the name of the function directly?

This is the most common use of the closure function.

def func ():    name = ' Eva '    def Inner ():        print (name)    return innerf = Func () f ()

The method of judging closure function __closure__

#输出的__closure__有cell元素: Is the closure function def func ():    name = ' Eva '    def Inner ():        print (name)    print (inner.__ closure__)    Return innerf = Func () f () #输出的__closure__为None: Not a closure function name = ' Egon ' def Func2 ():    def inner ():        Print (name)    print (inner.__closure__)    return Innerf2 = Func2 () f2 ()
def wrapper (): Money    = +    def func ():        name = ' Eva '        def Inner ():            print (Name,money)        Return inner    return FUNCF = wrapper () i = f () I ()
From urllib.request Import Urlopendef index ():    url = "http://www.xiaohua100.cn/index.html"    def get ():        return Urlopen (URL). Read ()    return Getxiaohua = index () content = Xiaohua () print (content)
Back to Top

Summary of this chapter

Namespaces:

A total of three namespaces range from large to small in order: built-in namespaces, global namespaces, local namespaces

Scope (including the scope chain of the function):

A small range can be used in a wide range of
But a large range cannot be used in small areas.
range from large to small (figure)

In a small area, if you want to use a variable that is present in this small range, use your own
If not in a small area, use the upper level, the upper level is not used, and so on.
If none, error

Nesting of functions:

Nested calls

Nested definitions: Functions that are defined internally cannot be called directly at the global

The nature of the function name:

is a variable that holds the memory address where the function resides.

Closures:

An intrinsic function contains a reference to an outer scope rather than a full-action domain name, which is called a closure function

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.