Python Learning Note 4: higher-order functions, adorners, generators, iterators

Source: Internet
Author: User
Tags function definition iterable

I. Advanced functions
1. Pass a function name as an argument to another function
2. The return value contains the name of the function
>>> def Bar ():
... print ("in the Bar")
...
>>> def foo (func):
... res=func ()
... return Res
...
>>> Foo (BAR)
In the bar

Two. Nesting functions
Define another function in a function

Three. Decorative Device
An adorner is essentially a function that decorates other functions and adds additional functionality to other functions.
Principle 1: Cannot modify the source code of the decorated function
Principle 2: Cannot modify the calling method of the decorated function
Functions and variables:
>>> def Bar ():
... print ("In the bar!")
>>> Bar ()
In the bar!
>>> F=bar
>>> F
<function Bar at 0x7f0b3bddba60>
>>> Bar
<function Bar at 0x7f0b3bddba60>
>>> F ()
In the bar!


Higher order functions + nested functions-"adorners"

Import time
def timer (func):
def deco (*args,**kwargs):
Start_time=time.time ()
Func (*args,**kwargs)
Stop_time=time.time ()
Print ("The Func run time is {time}". Format (Time=stop_time-start_time))
Return deco
@timer #test1 =timer (test1)
def test1 ():
Time.sleep (2)
Print (' In the Test1 ')
@timer
Def test2 ():
Time.sleep (2)
Print (' In the Test2 ')
Test1 ()
Test2 ()


In the Test1
The Func run time is 2.000096321105957
In the Test2
The Func run time is 2.0006771087646484

Four. Generator
1. The generator generates the corresponding data only when it is called
2. Only the current location is recorded, only one __next__ method

3. Generate Generator:
(1) Change the list generator's [] to ()
>>> l=[x*x for x in range (4)]
>>> L
[0, 1, 4, 9]
>>> g= (x*x for x in range (4))
>>> g
<generator Object <genexpr> at 0x7f0b3bde6e60>
>>>
(2) If a function definition contains the yield keyword, then this function is no longer a normal function, but a generator
def fib (max):
n,a,b=0,0,1
While n< Max:
Yield b
A,b=b,a+b
N+=1
Return "Done"
F=FIB (6)
Print (f)

D:\Programs\Python\Python35-32\python.exe e:/python/pylearn/oldboy/dayn/day4/genetor2.py
<generator Object fib at 0x01ba17e0>

4. Can also realize the effect of concurrency operation in single-threaded case by yield
Import time
DEF consumer (name):
Print ("%s ready to eat buns!") "%name)
While True:
Baozi=yield
Print ("Bun [%s] came, was [%s] eaten"% (baozi,name))
def producer (name):
C=consumer ("A")
C2=consumer ("B")
C.__next__ ()
C2.__next__ ()
Print ("Lao Tzu began to prepare buns!") ")
For I in range (10):
Time.sleep (1)
Print ("Made 1 buns, in two halves!") ")
C.send (i)
C2.send (i)
Producer ("Alex")

Operation Result:
A ready to eat steamed buns!
B prepare to eat steamed buns!
Lao Tzu began to prepare steamed buns!
Made 1 buns, in two halves!
Bun [0] came and was [A] eaten
Bun [0] came, was [B] eaten
Made 1 buns, in two halves!
Bun [1] came and was [A] eaten
Bun [1] came, was [B] eaten

Four. iterators
There are several types of data that can be directly acting on a For loop:

A class is a collection of data types, such as list, tuple, dict, set, str, and so on;

A class is generator, including generators and generator function with yield.

These objects that can directly act on a for loop are called an iterative object: Iterable.

You can use Isinstance () to determine whether an object is a Iterable object
The generator can not only be used for a for loop, but it can also be called by the next () function and return the next value until the last throw Stopiteration error indicates that the next value cannot be returned again.

An object that can be called by the next () function and continually returns the next value is called an iterator: Iterator
All objects that can be used for a for loop are iterable types;

All objects that can be used for the next () function are iterator types, which represent a sequence of lazy computations;

Collection data types such as list, Dict, str, and so on are iterable but not iterator, but a iterator object can be obtained through the ITER () function.

Python's for loop is essentially implemented by calling the next () function.

Python Learning Note 4: higher-order functions, adorners, generators, iterators

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.