Python fourth day

Source: Internet
Author: User
Tags closure

First

1. Nested invocation of function: Other functions are called in the process of calling the function. The code is simple and readable.

Example 1:

def foo ():

Print (' from foo ')


def bar ():

Print (' from Bar ')

Foo ()

Bar ()


#结果:

From Bar

from Foo


Example 2:

def max2 (x, y):

If x > Y:

return x

Else

Return y


def max4 (a,b,c,d):

Res1 = Max2 (A, B)

Res2 = Max2 (res1,c)

Res4 = Max2 (res2,d)

Return RES4


Print (MAX4 (1,4,2,5))


2. Nested definition of function: Inside a function, define another function.


Second

1. Namespace: Place where the name is stored, exactly where the name and the value of the variable are bound.

The namespaces in Python are:

1. Built-in namespaces: Generate and store some python-brought names when the Py is started.

Print (), Len (), Max () ...


2. Global namespace: The name defined at the file level when the file is executed.

X=1,

3, the local namespace: During the execution of the file, if the function is called, it will produce the function's local namespace, to hold the name defined within the function. Takes effect when the function is called and expires after the function call ends.


Load order of three namespaces:

Built-in and global--local

From top to bottom.


Query order for three namespaces:

Local-to-global

From the bottom up.


2, Scope: The scope of application of the role

Global scope: Globally valid, accessible from any location.

Global include: Globals

1. Built-in name

2. Global Name

Cases:

Def f1 ():

def f2 ():

Def f3 ():

Print (max)


F3 ()

F2 ()

F1 ()

<built-in function max>


Local scope: Temporary effective, locally valid.

Partially included: Locals

1. Local name

The global scope is still local to the global scope.


Dir View what methods are under the object.


#global keywords

Global

X=1

Def f1 ():

Global X

x=2

F1 ()

Print (x)

2


#不加global can also modify mutable types of data

L = []

def f2 ():

L.append (' F2 ')

F2 ()

Print (l) L = []

def f2 ():

L.append (' F2 ')

F2 ()

Print (L)


[' F2 ']


X=0

Def f1 ():

X=3

def f2 ():

x=2

Def f3 ():

Global X

X=3

F3 ()

F2 ()

F1 ()


Print (x)


3


X=0

Def f1 ():

X=3

def f2 ():

x=2

Def f3 ():

Global X

X=3

F3 ()

Print (x)

F2 ()

F1 ()


2


X=0

Def f1 ():

X=3

def f2 ():

x=2

Def f3 ():

nonlocal x

X=3

F3 ()

Print (x)

F2 ()

F1 ()

3


#优先掌握: A scope relationship is defined when the function is defined, regardless of the location of the call. Need to go back to the location of the original definition function to find the scope relationship


x= 1

Def f1 ():

def f2 ():

Print (x)

return F2


def foo (func):

x=100

Func ()


Foo (F1 ())

1


#此处值为1是因为作用域的定义在上面.

3, Closure function: closed, wrapped.

Defined:

1. Functions defined inside the function

2, contains a reference to the external role domain name Word, rather than the global role domain name Word to be referenced, then the intrinsic function is called the closure function.

Def f1 ():

x=2

def f2 ():

Print (x)

return F2


RES=F1 ()

Res ()

2


#此处的f2函数就是闭包函数, at this time he is not independent of his outer layer of the scope of the package.

Def deco ():

X=123123

def wrapper ():

Print (x)

Return wrapper

Wrapper ()


Func=deco ()

Func ()


123123


#查看外部变量

Import requests

def index (URL):

Def get ():

Print (Requests.get (URL). Text)

return get


Python_web=index (' http://www.python.org ')

Baidu_web=index (' http://www.baidu.com ')


Print (python_web.__closure__)


(<cell at 0x0000007e65ea55e8:str object at 0x0000007e66035df8>)


Import requests

def index (URL):

Def get ():

Print (Requests.get (URL). Text)

return get


Python_web=index (' http://www.python.org ')

Baidu_web=index (' http://www.baidu.com ')


Print (python_web.__closure__[0].cell_contents)


http://www.python.org


When the inner function of the closure is not covered by the scope, his scope is none

4, why to use the adorner?

1, the development of the closure principle: the expansion is open, the modification is closed.

Adorners: To add new features to others,

The adorner can be any callable object, and the adorned object can be any callable object.


2, the adorner needs to follow the principle:

2.1 Do not modify the source code of decorative objects

2.2 Do not modify the function of the called object

The goal is to satisfy 1 and 2 pieces to add new features


Example 1:

Import time

def index ():

Time.sleep (3)

Print (' Welcome to index ')


Def home ():

Time.sleep (3)

Print (' Welcome to Home ')


def Timmer (func):

def wrapper ():

Start=time.time ()

Func ()

Stop=time.time ()

Print (' Run time is%s '% (Stop-start))

Return wrapper


Index=timmer (Index)

Home=timmer (Home)


Index ()

Home ()


Shorthand decorator:

Import time

def Timmer (func):

def wrapper ():

Start=time.time ()

Func ()

Stop=time.time ()

Print (' Run time is%s '% (Stop-start))

Return wrapper


@timmer#装饰器需要在调用的上面

def index ():

Time.sleep (3)

Print (' Welcome to index ')

@timmer#@ equivalent Home=timmer (home)

Def home ():

Time.sleep (3)

Print (' Welcome to Home ')


Index ()

Home ()


#@ adorner name, must be written directly above the decorated object, and is a separate line


Example 2: Adding parameters to a modified object

Import time

def Timmer (func):

def wrepper (*args,**kwargs):

Start=time.time ()

Func (*args,**kwargs)

Stop=time.time ()

Print (' Run time is%s '% (Stop-start))

Return Wrepper


@timmer

def index ():

Time.sleep (2)

Print (' Welcome to index ')

@timmer

def home (name):

Time.sleep (2)

Print (' Welcome to%s '%name)


Index ()

Home (' home ')


Example 3: Return value

#对被修饰对象加参数

Import time

def Timmer (func):

def wrepper (*args,**kwargs):

Start=time.time ()

Res=func (*args,**kwargs)

Stop=time.time ()

Print (' Run time is%s '% (Stop-start))

return res

Return Wrepper


@timmer

def index ():

Time.sleep (2)

Print (' Welcome to index ')

Return 123

@timmer

def home (name):

Time.sleep (2)

Print (' Welcome to%s '%name)

Return 456


Res=index ()

Print (RES)

Res1=home (' home ')

Print (RES1)


>>

Welcome to Index

Run Time is 2.00014328956604

123

Welcome to Home

Run Time is 2.0002007484436035

456


Example 3: The function of user login authentication with adorners

cust_dic={' user ': None}

def auth (func):

def auth_toke (*args,**kwargs):

If cust_dic[' user ']:

return func (*args, **kwargs)

USER_INP = input (' user>> '). Strip ()

PASS_INP = input (' pass>> '). Strip ()

With open (' db ', ' R ', encoding= ' Utf-8 ') as Use_f:

Use_list=eval (Use_f.read ())

if user_inp = = use_list[0][' user '] and PASS_INP = = use_list[0][' password ']:

cust_dic[' user '] = USER_INP

return func (*args,**kwargs)

Else

Print (' Log in error ')

Return Auth_toke


@auth

def access ():

Print (' Login sessfull ')


@auth

def error (name):

Print (' Welcome to be%s '%name)


Access ()

Error (' JSON ')


>>:

User>> JSON

Pass>> 123123

Login Sessfull

Welcome to IS JSON


#闭包函数只需要用到3层就能满足一切函数的传参.

#装饰器补充

Import time

def foo ():

' This is the index function '

Time.time ()

Print (' Access ')

Return 123

# Print (Help (foo))


Print (foo.__doc__)


This is the INDEX function

#多个装饰器

Who is on top who takes effect first.

5. Iterators:

Iterations: Repetitive processes, each repetition is based on the last result.

The element that takes out the sequence type is the iteration

Example 1:

L = [' A ', ' B ', ' C ', ' d ']

Count=0

While Count < Len (l):

Print (L[count])

Count+=1


>>

A

B

C

D


5.1, Iterators: Remove non-sequential data, not by index.

5.2, can iterate object: General object has __iter__ method: Object. __iter__, the object is an iterative object.

The objects that can be iterated are: strings, lists, tuples, dictionaries.

Example 2:

dic={' name ': ' Egon '}

RES=DIC.__ITER__ ()

Print (res) #iterator iterator

Example 3:

dic={' name ': ' Egon ', ' Age ': 11}

RES=DIC.__ITER__ ()

Print (Next (res))

Print (Next (RES)

>>

Name

Age

#StopIteration Tip iterator has no value, it should stop.

Iterators themselves are also objects that can be iterated.

dic={' name ': ' Egon ', ' Age ': 11}

# res=dic.__iter__ ()

Res=iter (DIC)

Print (Next (res))

Print (Next (res))

>>

Name

Age

#当迭代器遇到stopiteration的时候会停止运行.

s= ' Hello '

L=[' A ', ' B ', ' C ', ' d ']

Iter_l=iter (L)

While True:

Try

Print (Next (iter_l))

Except stopiteration:

Break

>>

A

B

C

D

6. Iterator object:

6.1, has __iter__, the execution result is still the iterator itself

6.2, there is __next__, execute once to take a value

Advantages of Iterator objects:

1. Provide a unified (index-independent) iterative approach

2, the iterator itself, more memory than other data types

3. Iterators can hold an infinite number of values.


Example 1,

With open (' db ', encoding= ' utf-8 ') as F:

Print (Next (f))

Print (Next (f))

Print (Next (f))

Print (Next (f))


>>

111111111111111111111

11111111111111

11111111111

1111111

Iterator Disadvantage:

1, one-time, can not be returned back, rather than the index to take the value of flexibility.

An environment that occupies large memory cannot be indexed.

2, can not predict when the end, that is, the length can not be predicted.

The For loop is an iterator.

The object for a For loop is an iterative object.


How is it possible to determine whether an object is an iterative object? See if the object has a ITER method.

The file is an iterator. ****

7. Generator

Generator: Contains the yield keyword inside the function, then the result of the function is the generator

The generator is an iterator.

#yield的功能:

1, the function of the results of the generator (in an elegant way to encapsulate __iter__,__next__)

2, the function pauses and continues to run the state is by the yield

Example 1, the manual implementation of the Rang function.

def My_rang (start,stop):

While True:

If start = = Stop:

Raise Stopiteration

Yield start

Start+=1

For I in My_rang (1,3):

Print (i)

7.1, yield and return of the comparison?

Same: function with return value

Different: Return can only be returned once,


Example 2, taif-f |GREP implementation

Import time

def tail (filepath):

With open (filepath, ' R ') as F:

F.seek (0,2)

While True:

line = F.readline ()

If line:

Yield line

Else

Time.sleep (0.2)


def grep (patten,lines):

For line in lines:

If Patten in line:

Print (line,end= ")

grep (' Error ', tail (' db '))

8, three-dimensional expression:

True if the result of the if decision condition else is false

1 if 5>3 else 0

Output is 1, if 5 is greater than 3, otherwise output 0

9. List parsing

The way you create new lists efficiently, based on an existing list.

List parsing is an application of the Python iteration mechanism, which is commonly used to create new lists and is therefore used in [].


Example 1: Traditional way

L=[]

For n in range (11):

L.append (N)

Print (L)

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


Example 2: List resolution

l=[N for N in range (10)]

Print (L)

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


Example 3: Removing a number greater than 4 within 10

Traditional methods:

L=[]

For n in range (10):

If n >= 4:

L.append (N)

Print (L)

[4, 5, 6, 7, 8, 9]


List resolution:

l=[N for N in range (ten) if n >=4]

Print (L)

[4, 5, 6, 7, 8, 9]

10. Generator expression:

The generator expression does not really create a list of numbers, but instead returns a generator object that "yields" the entry after each calculation of an entry. The generator expression uses lazy computing or a mechanism called delay evaluation.

The sequence is too long, and you should consider the builder expression instead of the list resolution when you need to get only one element at a time.


n= (i**2 for I in range (11))

Print (N)

<generator object <genexpr> at 0x000000a5be8a1d00>#此处返回的是一个生成器的地址


The generator takes the value through the next method:


n= (i**2 for I in range (11))

# Print (N)

Print (Next (N))

Print (Next (N))

Print (Next (N))

Print (Next (N))


0

1

4

9


The generator takes the value to the element after the traversal is complete, throws the Stopiteration

n= (i**2 for I in range (11))

# Print (N)

While True:

Try

Print (Next (N))

Except stopiteration:

Break


This article from "Man should self-reliance" blog, please be sure to keep this source http://nrgzq.blog.51cto.com/11885040/1951622

Python fourth day

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.