Iterators in Python

Source: Internet
Author: User

One: The use of function names

1. memory address of Function name

def func ():     Print (" hehe ") Print (func) Result:<function func at 0x1101e4ea0>

2. Function names can be assigned to other variables

  

def func ():     Print (" hehe ") Print  #  assign a function as a variable to another variable #  function call func ()

3. Function names can be used as elements of a container class

deffunc1 ():Print("hehe")defFunc2 ():Print("hehe")deffunc3 ():Print("hehe") LST=[Func1, Func2, func3] forIinchlst:i ()

4. Function names can be used as arguments to functions

 def   func ():  print  ( "  eat?  "  )  def   Func2 (FN):  print  ( "  I am func2  "  ) FN ()  #   The line passed FN  print  ( "  I'm func2   " ) Func2 (func)  #   The function func is passed as a parameter to the FUNC2 parameter fn.  

5. Function names can be used as return values for 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

Two: Closures

A closure is a reference to an inner layer function, a variable of an outer layer function (non-global)

  

def func1 ():     " Alex "    def Func2 ():         Print # Closed Package     Func2 () func1 () Results: Alex    

We can use __CLOSURE__ to detect if a function is a closure, and the return cell is a closure, and none is returned.

  

def func1 ():     " Alex "    def Func2 ():         Print # Closed Package     Func2 ()    print(func2.  __closure__#  (<cell at 0x10c2e20a8:str object at 0x10c3fc650>,)func1 ()

Methods for calling intrinsic functions outside of a function:

def outer ():     " Alex "    # intrinsic functions    def inner ():         Print (name)     return  # Access external function, get function address to intrinsic function #  access intrinsic function

Similarly, when there are multiple layers of nesting:

def func1 ():     def Func2 ():         def func3 ():             Print (" hehe ")         return func3     return func2    func1 ( ) () ()

Benefits of using closures: the variables in the outer function can be guaranteed to reside in memory for use by the program behind it

Three: iterators

First, define a concept-an iterative object, Str,list,tuple,dict,set, which is an iterative object because it follows an iterative protocol to see all the methods defined in the class through the Dir () function, and if there is __iter__ in it, Then the object of this class is an iterative object. Iterable means an iterative object, and iterator means an iterator, which is two concepts.

L = [n/A]l_iter= L.__iter__() fromCollectionsImportiterable fromCollectionsImportIteratorPrint(Isinstance (l,iterable))#TruePrint(Isinstance (L,iterator))#FalsePrint(Isinstance (L_iter,iterator))#TruePrint(Isinstance (l_iter,iterable))#True

You can see that the iterator L executed the __iter__ () method has obtained an iterator l_iter, the iterator is not necessarily an iterator, but the iterator must be an iterative object, then how does the iterator run, and then look at a piece of code:

s ="I love Beijing Tian ' an gate"C= S.__iter__()#Get iteratorsPrint(c.__next__())#iterate using iterators. Get an element IPrint(c.__next__())#LovePrint(c.__next__())#NorthPrint(c.__next__())#BeijingPrint(c.__next__())#daysPrint(c.__next__())#AnnPrint(c.__next__())#DoorPrint(c.__next__())#stopiteration

It can be known that each time the iterator executes the __next__ () function returns an element of an iterative object, and when the iteration is completed and then executed __next__ () will error stopiteration, knowing the principle of the iterator, we look back at the principle of the For loop:

  

 for inch [[+]    : Print  = [All-in-a = lst.  __iter__() while True:    try:        = lst_iter.  __next__()        print(i)    except  stopiteration:          Break

Summarize:

Iterable: The object can be iterated. Contains the __iter__ () function internally
Iterator: Iterator. The internal contains __iter__ () and contains __next__ ().
Features of iterators:
1. Save memory.
2. Inertia mechanism
3. Cannot be repeated, only down execution.

Iterators in Python

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.