Python: The Path to day4 and pythonday4

Source: Internet
Author: User
Tags iterable

Python: The Path to day4 and pythonday4

Decorations (http://egon09.blog.51cto.com/9161406/1836763)

1. decorator: essentially a function;

The decorator (decorated with other functions) is to add additional functions for other functions;

Principle: 1. the source code of the decorated function cannot be modified;

2. The call method of the decorated function cannot be modified;

The decorator is completely transparent to the decorated function and does not modify the code and call method of the decorated function.

Implement the knowledge reserve of the decorator:

1. A function is a variable ";

2. High-order functions;

3. nested Functions

Higher-order functions + nested functions = "decorator

Anonymous functions (lambda expressions)

>>> Calc = lambda x: x * 3
>>> Calc (2)
6

Higher-order functions:

A. pass a function name as a real parameter to another function;

>>> Def bar ():
Print ("in the bar .....")

>>> Def foo (func ):

Print (func)
>>> Foo (bar)

<Function bar at 0x7f8b3653cbf8>  

B. The returned value contains the function name;

>>> Import time

>>> Def foo ():
Time. sleep (3)
Print ("in the foo .....")
>>> Def main (func ):
Print (func)
Return func
>>> T = main (foo)
<Function foo at 0x7fb7dc9e3378>
>>> T ()
In the foo .....

 

Decorator:

When the source code is not modified, calculate the program running time:

 

Import time

Def timmer (func ):
Def warpper (* args, ** kwargs): # warpper (* args, ** kwargs) Universal parameter. You can specify the parameter or not specify the parameter.
Start_time = time. time () # calculation time
Func ()
Stop_time = time. time ()
Print ("the func run time is % s" % (stop_time-start_time) # Calculate the function Runtime
Return warpper

@ Timmer # is equivalent to test1 = timmer (test1). Therefore, the function execution call is performed in the decorator.
Def test1 ():
Time. sleep (3)
Print ("in the test1 ")

Test1 ()
The running result is as follows:

In the test1
The func run time is 3.001983404159546

Decorator with parameters:

 

Import time

Def timmer (func ):
Def warpper (* args, ** kwargs ):
Start_time = time. time () # calculation time
Func (* args, ** kwargs) # execute the function and decorator Parameters
Stop_time = time. time ()
Print ("the func run time is % s" % (stop_time-start_time) # Calculate the function Runtime
Return warpper # returns the name of the inner function.

@ Timmer
Def test1 ():
Time. sleep (3)
Print ("in the test1 ")

@ Timmer # test2 = timmer (test2)
Def test2 (name ):
Print ("in the test2 % s" % name)

Test1 ()
Test2 ("alex ")
The running result is as follows:

In the test1
The func run time is 3.0032410621643066
In the test2 alex
The func run time is 2.3603439331054688e-05

Decorator return values:

 

Import timeuser, passwd = "alex", "abc123" def auth (func): def wrapper (* args, ** kwargs): username = input ("Username :"). strip () password = input ("Password :"). strip () if user = username and passwd = password: print ("\ 033 [32; 1 mUser has passed authentication. \ 033 [0 m ") return func (* args, ** kwargs) # actually executed function # res = func (* args, ** kwargs) # return res # function return value, because the decorator calls the function called by the decorator, so the return value is also in this function else: exit ("\ 033 [31; 1 mInvalid username or password. \ 033 [0 m ") return wrapperdef index (): print (" welcome to index page... ") @ authdef home (): # print (" welcome to home page... ") return" form home... "@ authdef bbs (): print (" welcome to bbs page ") index () print (home () bbs ()

 

Decorator with parameters:

Implementation: 1. Local verification; 2. remote verification

Import timeuser, passwd = "alex", "abc123" def auth (auth_type): ''' multi-layer nesting of the function. Run the ''print ("auth_type ", auth_type) def out_wrapper (func): def wrapper (* args, ** kwargs): print ("wrapper func args:", * args, ** kwargs) if auth_type = "local": username = input ("Username :"). strip () password = input ("Password :"). strip () if user = username and passwd = password: print ("\ 033 [32; 1 mUser has passed authentication. \ 033 [0 m ") func (* args, ** kwargs) # actually execute the called function # res = func (* args, ** kwargs) # return res # function return value, because the decorator calls the function called by the decorator, so the return value is also in this function else: exit ("\ 033 [31; 1 mInvalid username or password. \ 033 [0 m ") elif auth_type =" ldap ": print (" Wool lbap, silly .... ") return wrapper return out_wrapperdef index (): print (" welcome to index page... ") @ auth (auth_type =" local ") def home (): # print (" welcome to home page... ") return" form home... "@ auth (auth_type =" ldap ") def bbs (): print (" welcome to bbs page ") index () home () bbs () # No function, because no function is called, the function is called in the decorator. The decorator calls the function.

Iterator and Generator

Generator

By using the list generation method, we can directly create a list. However, due to memory restrictions, the list capacity must be limited. In addition, creating a list containing 1 million elements not only occupies a large storage space, but if we only need to access the first few elements, the space occupied by the vast majority of elements is wasted.

Therefore, if the list elements can be calculated by some algorithm, can we continue to calculate the subsequent elements in the loop process? In this way, you do not need to create a complete list to save a lot of space. In Python, this type of computing mechanism is called generator.

>>> L1 = (I for I in range (10 ))
>>> L1
<Generator object <genexpr> at 0x7f6a9fbcaeb8>
>>> L1. _ next __()
0
>>> L1. _ next __()
1
Generator: data is generated only when called;

Only the _ next _ () method is used for execution. This method can record the running status of the program. yield is used to generate iterator functions. (It can only be called in the future. You can only remember the current status rather than forward or backward. Therefore, the yield function can be used by the banking system to record the status ).

''' Use yield to Implement Asynchronous effects and send and receive messages ''' import timedef consumer (name ): '''consumer eat steamed stuffed bun model ''' print ("% s ready to eat steamed stuffed bun ...... "% name) while True: ''' loop, because '''baozi = yield print (" steamed stuffed bun % s was eaten by % s ...... "% (baozi, name) def producer (boss): ''' the producer produces the Steamed Stuffed Bun model. The producer produces the Steamed Stuffed Bun ''' c1 = consumer (" ") c2 = consumer ("B") c1. _ next _ () c2. _ next _ () ''' next, the producer will produce steamed stuffed buns, and pass it to the consumer ''' for I in range (1, 10): time. sleep (1) c1.send (I) c2.send (I) producer ("Alex ")

Run the following command:
A is preparing to eat steamed stuffed bun ......
B is going to eat steamed stuffed bun ......
Steamed Stuffed Bun 1 was eaten by ......
B ate Steamed Stuffed Bun 1 ......
Steamed Stuffed Bun 2 was eaten by ......
B ate Steamed Stuffed Bun 2 ......
Steamed Stuffed Bun 3 was eaten by ......
B ate Steamed Stuffed Bun 3 ......
Steamed Stuffed Bun 4 was eaten by ......
B ate Steamed Stuffed Bun 4 ......
Steamed Stuffed Bun 5 was eaten by ......
B ate Steamed Stuffed Bun 5 ......
Steamed Stuffed Bun 6 was eaten by ......
B ate Steamed Stuffed Bun 6 ......
Steamed Stuffed Bun 7 was eaten by ......
B ate Steamed Stuffed Bun 7 ......
Steamed Stuffed Bun 8 was eaten by ......
B ate Steamed Stuffed Bun 8 ......
Steamed Stuffed Bun 9 was eaten by ......
Steamed Stuffed Bun 9 was eaten by B .....

Iterator

We already know that it can be used directlyforThe following types of cyclic data are available:

The first type is the set data type, suchlist,tuple,dict,set,strAnd so on;

FirstgeneratorIncluding the generator andyieldGenerator function.

These can be directly appliedforCyclic objects are collectively referred to as iterative objects:Iterable.

Availableisinstance()Determine whether an object isIterableObject

>>> from collections import Iterable >>> isinstance ([], Iterable) True >>> isinstance ({}, Iterable) True >>> isinstance ( 'abc' , Iterable) True >>> isinstance ((x for x in range ( 10 )), Iterable) True >>> isinstance ( 100 , Iterable) False

 

 

 

 

 

 

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.