Introduction to adorners, generators, and iterators in Python

Source: Internet
Author: User
Tags exit in iterable ldap
Adorner ()

1, Adorner: essence is a function;

adorners (decorating other functions), is to add additional functions for other functions;

Principle: 1. Cannot modify the source code of the decorated function;

2. Cannot modify the calling mode of the decorated function;

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

Implement the Adorner Knowledge Reserve:

1. A function is a "variable";

2. Higher order functions;

3. Nested functions

Higher order function + nested function = "Adorner"

An anonymous function (lambda expression)

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

Higher order functions:

A. Pass a function name as an argument to another function;

>>> def bar (): Print ("In the Bar ...") >>> def foo (func): Print (func) >>> foo (bar) <funct Ion Bar at 0x7f8b3653cbf8>


B. The return value contains the name of the function;

>>> Import time>>> def foo (): Time.sleep (3) print ("In the Foo ...") >>> def Main (func): pri NT (func) return func>>> t = Main (foo) <function foo at 0x7fb7dc9e3378>>>> T () in the Foo .....

When the source code is not modified, the time that the program runs is:

Import Time

def Timmer (func):
def warpper (*args,**kwargs): #warpper (*args,**kwargs) Universal parameter, you can specify parameters or do not specify parameters
start_time = Time.time () #计算时间
func ()
stop_time = Time.time ()
print ("The Func Run time is%s"% (stop_time-start_time)) #计算函数的运行时间
return Warpper

@timmer # is equivalent to test1 = Timmer (test1), so the execution call of the function is executed within the adorner.
def test1 ():
Time.sleep (3)
print ("in the Test1")

test1 ()
The results of the operation are as follows:

In the Test1
The Func run time is 3.001983404159546

The case of the adorner with parameters:

Import Time

def Timmer (func):
def warpper (*args,**kwargs):
start_time = Time.time () #计算时间
func (*args,**kwargs) # execution function, adorner parameter condition
stop_time = Time.time ()
print ("The Func Run time is%s"% (stop_time-start_time)) #计算函数的运行时间
Return Warpper # returns the inner function name

@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 results of the operation are as follows:

In the Test1
The Func run time is 3.0032410621643066
In the Test2 Alex
The Func run time is 2.3603439331054688e-05

Adorner return value condition:

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;1muser has passed authentication.\033[0m ") return func (*args,**kwargs)   #实际上执行调用的函数               # res = func (*args,* *kwargs)            # return res #函数返回值的情况, because the adorner is called when the function is called in the adorner, so the return value is also in this function else:            exit ("\033[31;1minvalid username or password.\033[0m ") 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 ()

The case of the adorner with parameters:

Implementation: 1, local authentication, 2, Remote authentication

Import timeuser,passwd = "Alex", "abc123" def Auth (auth_type): Multi-layered nesting of functions, first performing the outer function ' 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 use                    r = = Username and passwd = = Password:print ("\033[32;1muser has passed authentication.\033[0m")  Func (*args,**kwargs) #实际上执行调用的函数 # res = func (*args,**kwargs) # return Res #函数返回值的情况, because the adorner is called when the function is called in the adorner, so the return value is also else:exit in this function ("\033[31;1minvalid username or password.\0 33[0m ") elif Auth_type = =" LDAP ": Print (" Knitting lbap, dumb .... ")    ") return Wrapperreturn 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 () #函数没有, because there is no calling function, function calls inside the adorner, is the adorner called the function 

  Iterators and generators

Generator

With list generation, we can create a list directly. However, with memory limitations, the list capacity is certainly limited. Also, creating a list of 1 million elements takes up a lot of storage space, and if we just need to access the first few elements, the vast majority of the space behind it is wasted.

So, if the list element can be calculated according to an algorithm, can we continue to calculate the subsequent elements in the process of the loop? This eliminates the need to create a complete list, which saves a lot of space. In Python, this side loop computes the mechanism, called the generator: Generator.

>>> L1 = (I for I in range (10))
>>> L1
<generator Object <genexpr> at 0x7f6a9fbcaeb8>
>>> l1.__next__ ()
0
>>> l1.__next__ ()
1
Generator: The corresponding data is generated only when it is called;

This is done only through the __next__ () method, which records the state of the program's operation, and yield is used to generate an iterator function. (can only be called back, not forward or backward, only remember the current state, so the bank's system used to record the use of the yield function).

%=  %= Consumer (= consumer (i  range) runs as follows: A ready to eat steamed buns ... b ready to eat steamed buns ... Bun 1 was eaten by a ... Bun 1 was eaten by b ... Bun 2 was eaten by a ... Bun 2 was eaten by b ... Bun 3 was eaten by a ... Bun 3 was eaten by b ... Bun 4 was eaten by a ... Bun 4 was eaten by b ... Bun 5 was eaten by a ... Bun 5 was eaten by b ... Bun 6 was eaten by a ... Bun 6 was eaten by b ... Bun 7 was eaten by a ... Bun 7 was eaten by b ... Bun 8 was eaten by a ... Bun 8 was eaten by b ... Bun 9 was eaten by a ... Bun 9 was eaten by b .....

Iterators

We already know that for there are several types of data that can be directly acting on a loop:

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

One is generator to include the generator and yield the generator function with the band.

These objects, which can be directly applied to for the loop, are called iterative objects: Iterable .

You can use to isinstance() determine whether an object is an Iterable object

>>> from Collections Import iterable>>> isinstance ([], iterable) true>>> isinstance ({}, iterable) true>>> isinstance (' abc ', iterable) true>>> isinstance ((x for X in range), iterable) True >>> isinstance (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.