Python function object, generator, adorner, iterator, closure function

Source: Internet
Author: User
Tags closure object model

First, the Function object

A proper understanding of Python functions can help us to better understand the high-order techniques of Python decorators, anonymous functions (lambda), functional programming, and so on.

Functions are an integral part of the programming language, which is commonplace. But a function as the first class object (first-class object) is a major feature of the Python function. So what exactly is the first class of objects (First-class object)?

Everything in Python is an object, and the function as the first class object has the following characteristics:

#函数身为一个对象, owns three common properties of the object model: ID (memory address), type, and Value def foo (text):    return len (text) print (Type (foo)) #函数类型print (ID (foo)) # Function ID   memory address print (foo) #函数值

    • You can assign a value as a variable
#函数可以被引用, that is, a function can assign a value to a variable
#!/usr/bin/env python#-*-coding:utf-8-*-def foo ():    print (' from foo ') foo () Func=foo    #引用, assignment print (foo) print ( Func) func ()

Output:
from Foo
The memory address indicates that Func refers to the Foo function address, that is, Foo assigns the address to the Func variable
<function Foo at 0x0000000002063e18>
<function Foo at 0x0000000002063e18>
    • Elements that can be used as container types (collections)
#容器对象 (list, dict, set, etc.) can hold any object, including integers, strings, functions can also be stored in the container Object Def foo ():    print ("Hanjialong") dif={"func": foo}# foo () if __name__ = = ' __main__ ':    dif={"func": foo}    dif["func"] () #比较函数地址def foo ()    : Print ("Hanjialong") dif={ "Func": Foo}print (foo)    # dif={"func": foo}    # dif["func"] () print (dif["func"])
    • Pass to other functions as arguments
def foo (name): #传入数据类型并计算长度    size = Len (name)    return size #将结果returndef Show (func):    size = func ("JJJJJ") # Equivalent to running the Foo function inside the show function, size accepts the return result of the Foo function    print ("Length of string is%s"%size)
Show (foo)
    • Can be used as the return value of a function
"" "function accepts one or more functions as input or function output (return) value is a function, we call such function as the higher order function" "" Def foo ():    print ("return value") def Bar (func):    return FUNCF = Bar (foo) f () bar (foo ())
    • function nesting
1, nested call # nested function of the meaning of the equivalent of a large demand to split into a number of small requirements and then combined with the following as an example MAX2 function to do two worth of size for example, if you want to do more than 10 100, you need to combine Def max2 (x, y) in max4:    return x if x > y else ydef max4 (a,b,c,d):    res1=max2 (A, B)    res2=max2 (res1,c)    res3=max2 (res2,d)    return Res3print (Max4 (10,99,31,22)) 2, function nesting definition
#函数的嵌套定义
Def f1 (): #第一步进入f1函数
def f2 (): #第二部f1函数体中有f2函数声明
Print (' from F2 ')
Def f3 (): #第四部f2函数体中有f3函数声明
Print (' from F3 ')
F3 () #第五部f2函数体中运行f3函数
F2 () #第三部f1函数体重运行f2内容


F1 ()

second, namespace and scope

1. Namespace definitions

Namespaces are mappings of names and objects, like dictionaries, where key is the variable name and value is the variable

#定义名字的方法import timename= ' Egon ' #定义变量def func (): #定义函数    passclass Foo: #定义类    Pass

2. Classification of namespaces

    • Built-in namespaces: As the Python interpreter starts, it includes exception types, built-in functions, and special methods, which can be called anywhere in the code
Print (sum) print (max) print (min) print (max ([builtinsfor]) import i in Dir (builtins): #打印所有的内置函数 print (i) Copy code result: C: \python\python36\python.exe d:/python/Courseware/day4/cc.py<built-in function sum><built-in function max>< Built-in function min> 3ArithmeticErrorAssertionErrorAttributeErrorBaseExceptionBlockingIOErrorBrokenPipeErrorBufferErrorBytesWarningChildProces Serrorconnectionabortederrorconnectionerrorconnectionrefusederrorconnectionreseterrordeprecationwarningeoferrorellipsisen Vironmenterrorexceptionfalsefileexistserrorfilenotfounderrorfloatingpointerrorfuturewarninggeneratorexitioerrorimporterro Rimportwarningindentationerrorindexerrorinterruptederrorisadirectoryerrorkeyerrorkeyboardinterruptlookuperrormemoryerrorm Odulenotfounderrornameerrornonenotadirectoryerrornotimplementednotimplementederroroserroroverflowerrorpendingdeprecationw Arningpermissionerrorprocesslookuperrorrecursionerrorreferenceerrorresourcewarningruntimeerrorruntimewarningstopasynciter AtionstopiteratIonsyntaxerrorsyntaxwarningsystemerrorsystemexittaberrortimeouterrortruetypeerrorunboundlocalerrorunicodedecodeerrorunico Deencodeerrorunicodeerrorunicodetranslateerrorunicodewarninguserwarningvalueerrorwarningwindowserrorzerodivisionerror __build_class____debug____doc____import____loader____name____package____spec__ Absallanyasciibinboolbytearraybytescallablechrclassmethodcompilecomplexcopyrightcreditsdelattrdictdirdivmodenumerateevale Xecexitfilterfloatformatfrozensetgetattrglobalshasattrhashhelphexidinputintisinstanceissubclassiterlenlicenselistlocalsma Pmaxmemoryviewminnextobjectoctopenordpowprintpropertyquitrangereprreversedroundsetsetattrslicesortedstaticmethodstrsumsup Ertupletypevarszipprocess finished with exit code 0
    • Global namespaces: The execution of a file produces a global namespace, meaning that the name of a file-level definition is placed in that space
X=1 #全局命名空间def func ():     money=2000   #非全局    x=2 print    (' func ', x) #打印的是x the value of =2 if there is no global print (x) # The print is global print (func) func ()
    • Local namespaces: A local namespace is generated when the function is called, and is only temporarily bound when the function is called, and the call ends the unbind

x=10000 #全局def func ():    x=1 #局部    def f1 ():        Pass

3. Scope

    • 1. Global scope: Built-in namespaces, global name layer space
    • 2. Local function: local name space
Name Lookup Order: Local Namespace---"Global namespace---" Built-in namespaces

Python function object, generator, adorner, iterator, closure function

Related Article

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.