Python's heavy device (builder, iterator, adorner)

Source: Internet
Author: User
Tags iterable

First, the decoration device

1, definition: The essence is the function, decorate other functions is to add the attachment function for other functions.

2. Principle:

A. Cannot modify the source code of the decorated function;

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

Instance:

#!/usr/bin/env python
#-*-Coding:utf-8-*-
#Author: Ye

Import time

#装饰器
def Time_cha (func): #func等于test
   Time_start = Time.time ()
   Func () #此时func () equivalent to test ()
   Time.sleep (2)
   Time_stop = Time.time ()
   Print ("The Time Cha is:%s"% (Time_stop-time_start))

#主函数
def test ():
   Print ("*")
   Time.sleep (1)
   Print ("*")
   Time.sleep (1)
   Print ("In the Test")

#单独调用主函数
Test ()

#将装饰器套用在主函数上
Time_cha (test) #此方式改变了主函数的调用方式

3. Realize the knowledge reserve of the decorator:

A. function is "variable"

B. Higher-order functions

B1. Passing a function name as an argument to another function (adding its function without modifying the decorated function)

Instance:

def test1 (): #此函数时源代码
Print ("In the Test1")

def test2 (func): #此函数时装饰器
Print ("In the Test2")
Print (func) #打印test1的内存地址
Func () #这里相当于test1 ()

Test1 ()
Test2 (test1) #将test1这个函数名作为实参传递给test2, thus realizing the higher order function

B2. The return value contains the function name (does not change the function (source code) call method)

Instance:

def test1 (): #源代码
Print ("In the Test1")

def test2 (func): #装饰器
Print ("In the Test2")
Func ()
Return test1# the function name as the return value by return

Test1 = Test2 (test1) #此处是test1函数名的内存地址
Test1 () #执行test1函数

C. Nested functions

def test1 (): #第一层函数
Print ("In the Test1")

Def test2 (): #第二层函数
Print ("In the Test2")

Test2 () #第一层函数执行时, call the second-level function

Test1 () #执行第一层函数

4, the case analysis of the adorner:

Case background: First define two modules, Europe and the United States and Henan Zone, two zones use the premise is to log in.

Step one: First realize the two zones of free login access;

Step Two: Define the Login module, and then use the login module as an adorner, decorated in Europe and the United States and Henan area

Step three: When the call to two zone module, then the login verification, can not be called before the validation (this involves the use of nested functions)

Status = False #初始化登录状态, false means not logged in, True indicates login

def login (func): #定义登录模块 (Adorner function)
def inner (): #定义嵌套函数
_uername = "Zhangye" #定义用户数据
Global Status #将函数内变量全局化

If status ==false: #根据状态判断是否需要登录
Username = input ("Please enter user name:")
If username = = _uername:
Print ("Welcome ...")
Status = True #登录成功后, converts the default state from False to True
If status = = True:
Print (func)
Func ()
Return inner #未调用时, not validated, only returns a second-level function name (verifies function name)

@login #还未到真正调用函数的地方, so no login verification is required here, only the second-level function name is returned.
Def America ():
Print ("* * * * * * * *)")

@login #还未到真正调用验证函数的地方, so no login verification is required here, only the second-level function name is returned.
def Henan ():
Print ("* * * * * Henan Area * * * * * *)

America () #调用时, executes the second-level function. Because it's got the second-level function name.
Henan () #调用时, executes the second-level function. Because it's got the second-level function name.

Second, 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.

There are a number of ways to create a generator. The first method is simple, as long as a list of the generated formula is [] changed () to create a generator:

Example one:

data = [1,2,3,4,5,6,7,8,9,]

   #列表生成式 (forced notation) 
data = [i*2 If i > 4 else I for I in data]
Print (data) == "[1, 2, 3, 4, ten, 4, +, +]

#列表生成器 (generated when data is used)
Data2 = (i*2 if i > else I for I in data)
Print (DATA2)
= = <generator object <genexpr> at 0x000002797c151db0>

Summary: The generator generates the corresponding data only when it is called.

Instance Two,
import time

#定义消费者模型函数

def Consumer (name): Print ("%s ready to eat buns!") "%name)
  Baozi = yield 
Print ("Bun [%s] came, eaten by [%s]!" "% (baozi,name))

#定义生产者模型函数
def producer (name):
c_a = Consumer (" a ")
C_b = Consumer (" B ")
C_ a.__next__ ()
c_b.__next__ ()
Print ("Lao Tzu began to be ready to make buns!")
for I in range:
Time.sleep (1)
Print ("Made 2 buns!") ")
C_a.send (i)
C_b.send (i)

producer (" Alex ")


III , iterators
We know that there are several types of data that can be directly applied to a for loop:
One is the collection data type: such as LIST,TUPLE,DICT,SET,STR, etc.; the
class is generator, Includes the generator and the generator function with yield.
These objects that can act directly on a for loop are called iterative objects, and iterable
can use Isinstance () to determine whether an object is a iterable object:

From collections Import iterable

#判断字符串是否可迭代
data = "ABC"
Print (Isinstance (data,iterable)) #=== "True

#判断列表是否可迭代
data = [+ +]
Print (Isinstance (data,iterable)) #=== "True

#判断字典是否可迭代
data = {1: "Ye", 2: "Zhang", 3: "Alex"}
Print (Isinstance (data,iterable)) #=== "True

#判断元组是否可迭代
Data = (+/-)
Print (Isinstance (data,iterable)) #=== "True

Note 1: An object that can be called by next() a function and continually returns the next value is called an iterator: Iterator .
Note 2: Dictionaries, collections, tuples, strings, and so on are iterative objects, but not iterators. However, an iterator can be obtained from the ITER () function.

  

    

Python's heavy device (builder, iterator, adorner)

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.