Python learning-iterator & amp; generator & amp; modifier, python Learning

Source: Internet
Author: User

Python learning-iterator & generator & decorator, python Learning

1. iterator

An iterator is a way to access collection elements. The iterator object is accessed from the first element of the set until all elements are accessed. The iterator can only go forward without moving back. One advantage of the iterator is that it does not require that all elements in the entire iteration process be prepared in advance. The iterator calculates an element only when it iterates to an element. Before or after this, the element may not exist or be destroyed. This feature makes it especially suitable for Traversing large or infinite sets.

Features:

Generate an iterator:

 1 >>> a= iter([1,2,3,4,5]) 2 >>> a 3 <list_iterator object at 0x0044ADF0> 4  5 >>> a.__next__() 6 1 7 >>> a.__next__() 8 2 9 >>> a.__next__()10 3

 

Ii. Generator

When a function is called, an iterator is returned. This function is called a generator. If the function contains the yield syntax, this function will become a generator.

Code:

 

1 #! /Usr/bin/env python 2 #-*-coding: UTF-8-*-3 ''' 4 # @ time: 5 # @ author: huange 6 # @ version: 1.1 7 # @ file: test2.py 8 # @ Software: PyCharm 9 ''' 10 11 def out_money (totle ): 12 13 while totle> 15 totle-= 116 17 yield 1 # yield returns a value of 18 19 20 ATM = out_money (3) 21 22 print ("Get money % s ten thousand" % ATM. _ next _ () 23 24 print ("spent! ") 25 26 print (" Get the money % s ten thousand "% ATM. _ next _ () 27 28 print (" spent! ") 29 30 print (" Get the money % s ten thousand "% ATM. _ next _ () 31 32 print (" spent! ") 33 34 print (" get $ % s 000 "% ATM. _ next _ () # The money will be lost at this time, and an error 35 36 print ("Get the money % s 000" % ATM will be reported. _ next __())

The main effect of yield is that it can interrupt the function and save the interrupt status. After the interruption, the code can continue to be executed. After a while, you can call this function again, run the command from the next sentence of yield.

You can use yield to implement concurrent operations in the case of a single thread.

1 #! /Usr/bin/env python 2 #-*-coding: UTF-8-*-3 ''' 4 # @ time: 5 # @ author: huange 6 # @ version: 1.1 7 # @ file: test2.py 8 # @ Software: PyCharm 9 ''' 10 11 import time12 13 def consumer (name): 14 print ("% s ready to eat steamed stuffed bun! "% Name) 15 while True: 16 baozi = yield # yield received 17 print (" steamed stuffed bun [% s] by sending () method, "% (baozi, name) 18 19 def producer (name): 20 c1 = consumer ('A ') 21 c2 = consumer ('B') 22 c3 = consumer ('C') 23 24 c1. _ next _ () 25 c2. _ next __() 26 c3. _ next _ () 27 28 print ("% s started preparing for the steamed stuffed bun! "% Name) 29 30 for I in range (10): 31 time. sleep (1) 32 print ('Made 3 Steamed Stuffed Bun ') 33 c1.send (I) 34 c2.send (I) 35 c3.send (I) 36 37 producer ('hh ')


3. decorator

1 #! /Usr/bin/env python 2 #-*-coding: UTF-8-*-3 ''' 4 # @ time: 5 # @ author: huange 6 # @ version: 1.1 7 # @ file: decorator. py 8 # @ Software: PyCharm 9 ''' 10 11 # @ login, perform the following operations: 12 #1. execute the login function and use the function under @ login as the parameter of the login function. That is, @ login is equivalent to login (movie) 13 #2. • assign the returned value of the executed login function to function 14 15 def login (func): 16 def inner (* args, ** kwargs) of the function under @ login ): 17 print ("login success... ") 18 return func (* args, ** kwargs) 19 return inner20 21 def home (): 22 print (" welcome to Home... ") 23 24 25 @ login26 def movie (name, passwd): 27 print (" welcome [% s] [% s] to movie .... "% (name, passwd) 28 29 @ login30 def music (name): 31 print (" welcome [% s] to music... "% name) 32 33 movie ('huhuanc', '000000') 34 music ('huhuanc') 35 home ()

As shown above: the decorated function has different numbers of parameters. Therefore, the decorator needs dynamic parameters!

A function can be decorated by multiple decorators:

1 #! /Usr/bin/env python 2 #-*-coding: UTF-8-*-3 ''' 4 # @ time: 5 # @ author: huange 6 # @ version: 1.1 7 # @ file: decorator. py 8 # @ Software: PyCharm 9 ''' 10 # verify the 11 def login (func): 12 def inner (* args, ** kwargs ): 13 print ("login success... ") 14 return func (* args, ** kwargs) 15 return inner16 17 # verify if it is a member user 18 def member (func): 19 def inner (* args, ** kwargs): 20 print ("welcome member... ") 21 return func (* args, ** kwargs) 22 return inner23 24 def home (): 25 print (" welcome to Home... ") 26 27 # @ login: 28 #1. execute the login function and use the function under @ login as the parameter of the login function. That is, @ login is equivalent to login (movie) 29 #2. • assign the returned value of the executed login function to function name 30 @ login31 @ member32 def movie (name, passwd) of the function under @ login ): 33 print ("welcome [% s] [% s] to movie .... "% (name, passwd) 34 35 @ member36 @ login37 def music (name): 38 print (" welcome [% s] to music... "% name) 39 40 movie ('huhuanc', '000000') 41 music ('huhuanc') 42 home ()

 

The decorator contains parameters:

1 # authentication function 2 def auth (request, kargs): 3 print ("authentication successful! ") 4 # log function 5 def log (request, kargs): 6 print (" log added successfully ") 7 # decorator function. Receives two parameters, which must be the name of a function. 8 def Filter (auth_func, log_func): 9 # The first layer of encapsulation. The f1 function is actually passed to the main_fuc parameter 10 def outer (main_func): 11 # Layer 2 encapsulation, the parameter values of auth and log functions are passed here 12 def wrapper (request, kargs): 13 # The Judgment logic of the following code is not important, it is important that the parameter reference and return value 14 before_result = auth (request, kargs) 15 if (before_result! = None): 16 return before_result; 17 18 main_result = main_func (request, kargs) # function to be decorated 19 if (main_result! = None): 20 return main_result; 21 22 after_result = log (request, kargs) 23 if (after_result! = None): 24 return after_result; 25 26 return wrapper27 return outer28 # note that the decorator function here has parameters, it means to first execute the filter function 29 # And then return the return value of the filter function as the name of the decorator function. So, 30 # Actually, here, Filter (auth, log) = outer, @ Filter (auth, log) = @ outer31 @ Filter (auth, log) 32 def f1 (name, age ): 33 34 print ("% s connecting business department 1 data interface ...... "% name) 35 36 # Call method 37 f1 (" jack ", 18) 38 39 Results: 40 authentication successful! 41 jack is connecting to business department 1 data interface... 42 log added successfully

 

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.