Applications, closures, and iterators for Python function names

Source: Internet
Author: User
Tags closure iterable

Application of function name (First class object) The function name is a variable, but it is a special variable that can be executed in conjunction with parentheses. 1. memory address of Function name
def func ():     Print (" haha ") Print (func)  # <function func at 0x000002750a7998c8>
2. Function names can be assigned to other variables
def func ():     Print (" haha ") Print  = func #把函数当成一个变量赋值给另一个变量a () #函数调用 func ()#<function func at 0x00000211e56198c8 ># haha
3. Function names can be used as elements of a container class
deffunc1 ():Print("haha")defFunc2 ():Print("haha")deffunc3 ():Print("haha")defFunc4 ():Print("haha") LST=[func1,func2,func3] forIinchlst:i ()#haha#haha#haha
View Code4. Function names can be used when the parameters of a function
deffunc ():Print("did you eat?")defFunc2 (FN):Print("I'm Func2 .") fn ()Print("I'm Func2 .") Func2 (func)#The function func is passed as a parameter to the FUNC2 parameter Fu#I'm Func2 .#did you eat?#I'm Func2 .
View Code5. Function names can be used as return values of functions

 

deffunc_1 ():Print("here is the function 1")    deffunc_2 ():Print("here is the function 2")    Print("here is the function 1")    returnFUNC_2FN= Func_1 ()#Execute function 1, function 1 returns the function 2, when FN points to the above function 2FN ()#perform the functions returned above#here is the function 1#here is the function 1#here is the function 2
View CodeClosure closure: The advantages of local variables accessing the outer function in the inner layer function:

1 Protect your variables from external influences

2. Allows the variable to reside in memory

Writing:

def outer ():

A = 10

def inner ():

Print (a)

Retunt Inner

Judging method:

def func ():     = Ten    def  Inner ():        print(a)    print(inner.  __closure__#  If the print is none. It's not a closure. If not none, it is the closure func ()
Three, iterators

Use Dir to see which methods the data contains

Print(dir (str))#Results['__add__','__class__','__contains__','__delattr__','__dir__','__doc__','__eq__','__format__','__ge__','__getattribute__','__getitem__','__getnewargs__','__gt__','__hash__','__init__','__init_subclass__','__iter__','__le__','__len__','__lt__','__mod__','__mul__','__ne__','__new__','__reduce__','__reduce_ex__','__repr__','__rmod__','__rmul__','__setattr__','__sizeof__','__str__','__subclasshook__','Capitalize','Casefold','Center','Count','encode','EndsWith','Expandtabs','Find','format','Format_map','Index','isalnum','Isalpha','Isdecimal','IsDigit','Isidentifier','Islower','IsNumeric','isprintable','isspace','Istitle','Isupper','Join','Ljust','Lower','Lstrip','Maketrans','Partition','Replace','RFind','Rindex','Rjust','rpartition','Rsplit','Rstrip','Split','Splitlines','StartsWith','Strip','Swapcase','title','Translate','Upper','Zfill']
View Code

Used to traverse lists, strings, tuples ... Wait, you can iterate over an object

Iterative objects: Iterable, __iter__ () can get iterators, no __next__ ()

Iterators: iterable, which have __iter__ () to get iterators, and __next__ ()

Features of iterators:

1. Only forward

2. Inertia mechanism

3. Save Memory (Generator)

Internal mechanism for the For loop

1. First get to the iterator

2. Using the while loop to get the data

3.it.__next__ () to get the data

4. Handling Exceptions try:xxx except stopiteration:

s ="I'm a little painter ."it= S.__iter__() while1:    Try: El= it.__next__()        Print(EL)exceptstopiteration: Break#I'm#is a#a#name#Small#painting#Home
View Code

Judging method:

s ="ABC"it= S.__iter__()#The first of these methodsPrint("__iter__" inchDir (it))#output is ture description is an iterative objectPrint("__next__" inchDir (it))#output is ture description is iterator#The second method of fromCollectionsImportiterable fromCollectionsImportIteratorPrint(Isinstance (it,iterable))#determine if the object is iterativePrint(Isinstance (It,iterator))#Judging is not an iterator
View Code

Applications, closures, and iterators for Python function names

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.