The path of the python's walking hole

Source: Internet
Author: User
Tags closure function definition iterable

# # # Python's continuation walk function pit
The previous article briefly introduced some of the functions of the simple use, this time continue to trample the function of the pit
1. Function objects
The function can also be passed as a parameter to another function, or it can be assigned to another, and both of these memory addresses are a
Kind of
Def f1 ():
Print (' This is a referenced function test ')
Func = F1
Print (F1) # No parentheses for the memory address of the Foo function this is actually very useful, explained later
Print (func) # func points to Foo memory address
Func () # foo memory address, plus () execute

# # #函数可以被引用
# def F1 ():
# print (' This is a referenced function test ')
#
# func = F1
# print (F1) # No parentheses are the memory address of the Foo function
# print (func) # func points to Foo memory address
# func () # foo memory address, plus () execute

######## #函数可以当做参数
# def F ():
# print (' This was from F ')
#
# def F2 (func): # # # #这里就是吧把函数当做一个参数传递进去
# func ()
# print (' This was from F2 ')
# F2 (f)
########## #函数可以作返回值
# def foo ():
# print (' from foo ')
# def Bar (func):
# return Func
# F=bar (foo)
# print (f)
# f ()
# ‘‘‘
# results
# <function Foo at 0x7f9491f04f28>
# from Foo
# ‘‘‘
########## #函数可以当作容器类型的元素

# # # The Container object (list, dict, set, etc.) can hold any object, including integers, strings, functions can also be stored in the container object
# # # # # # # # # # # # # # # # # # # # This is used in my practice,

def foo ():
Print (' from foo ')
dic={' func ': foo}
Foo ()
Print (dic[' func ')
Dic[' func '] ()

* * Examples are as follows

def select (SQL):
Print (' ========>select ')

def insert (SQL):
Print (' ========>add ')

def delete (SQL):
Print (' =======>delete ')

def update (SQL):
Print ('-=---->update ')
func_dic={
' Select ': SELECT,
' Update ': Update,
' Insert ': INSERT,
' Delete ':d elete
}

def main ():
While True:
sql = input (' sql: '). Strip ()
If not sql:continue
L = Sql.split ()
cmd = l[0]
If cmd in func_dic:
Func_dic[cmd] (L)


#按照以前的思路肯定这么写, write very much, and many are repeated, using the above method is very simple ....

def main ():
While True:
sql = input (' sql: '). Strip ()
If not sql:continue
L = Sql.split ()
If ' select ' = = L[0]:
Select (L)
If ' update ' = = L[0]:
Update (L)
If ' delete ' = = L[0]:
Delete (L)
If ' insert ' = = L[0]:
Insert (L)

# # #函数的嵌套
# x= 1
# def f (x):
# # print (x)
# def f2 (x):
# Print (x)
# def f3 (x):
# Print (x)
# F3 (2)
# F2 (3)
# f (4)


#如果函数里面没有写f3 (2), F2 (3) This kind of stuff, then he wouldn't have any output

# # # #原因很简单, look at the example below, I've defined three functions, but when I call I just call the F () function,
# # #f2 (), F3 () These two functions, although defined, but I do not call (note that although I F2 () and F3 () in the large function f (), but
# # # #他没有被调用啊, though you call F (), but he won't take the initiative to invoke something inside of his own function

x= 1
def f (x):
Print (x)
def f2 ():
Print (' from 2 ')
Def f3 ():
Print (' From3 ')
# F3 (2)
# F2 (3)
F (4)


2. Talking about the namespace and scope of the function
Let's talk about how to define a name.
Import time

Name = ' Lisi '

def foo ():
Pass
Class Foo:
Pass

These are all definitions of a name, and when you call it, if it's not defined as above, then you'll be quoted the error ' Nameerror:name ' name ' is not
Defined ' means defining a name when we import the package name definition function Definition class to define a variable.
It can be simply understood as a variable that is declared (personally, not very accurate).


There are three types of function namespaces in Python
1. Built-in namespaces
This is generated with the start of the Python interpreter, such as:
Max ()
Min ()
SUM ()

2. Global namespace: The execution of a file produces a global namespace, meaning that the name of the file-level definition is placed in the space
In my understanding is a global variable meaning, for Python, very good judgment, is shelf write. There is no space in front of the kind.
#x =1
# if x ==1:
# y=2
# import Time
# def func ():
# Pass
#
# class Foo:
# Pass

3 Local namespaces: A local namespace is generated when the function is called, and is only temporarily bound when the function is called, and the call ends the unbind
Which means it only takes effect inside the function.
# x=10000
# def func ():
# x=1
# def F1 ():
# Pass
Print (x) # #这里的x打印的不是1, but 10000

Scope in Python: An Zhaobo The main superficial understanding is the scope of the ' variable ' that you define,
Scope of scopes:
1. Global scope: Global namespace, built-in namespace
2. Local scope: Local namespace

Lookup Order of names (' variables '): Overall local scope-----> global scope
Local namespace---> Global namespaces---> Built-in namespaces


#查看全局作用域内的名字: Gloabls ()
#查看局局作用域内的名字: Locals ()
He returned the format of a dictionary, print (Gloabls ()), print (Locals ())
Can see if the function inside is global or local

Effective Duration:
#全局作用域: Globally valid, can be accessed anywhere, unless del is deleted, it will survive until the file execution is complete
#局部作用域的名字: Locally valid, can only be called at the local scope, only valid when the function is called, and the end of the call is invalidated.
Chestnuts:
x=111
Def f1 ():
def f2 ():
Print (x)
Def f3 ():
x=1000
Print (x)
F3 () # # #先找自身, find that return
F2 () # # # #这个找自身的范围, itself did not find a level, the upper level did not look up
F1 ()
Result: This can be a good indication of the scope
"' 111
111
1000
‘‘‘


3. Closure function:
==========
Closures, as the name implies, encapsulate an already existing function, but he encapsulates not only himself, but also the upper-level scope
A way to nest functions, you must observe the following rules:
A. Definitions in intrinsic functions
B. Contains a reference to an outer scope instead of a global scope, and the intrinsic function becomes a closure function

Simple chestnuts:
def foo ():
x=1000
def bar ():
Print (x)
Return Bar # # #注意这里返回的是一个内存地址 instead of the function result

Print (foo ())
#这里打印的是一个内存地址, not the result of course if you want to use Foo, then you can foo () ()
f = foo ()
F ()
Application:
Lazy calculation:
From urllib.request import Urlopen
def index (URL):
Def get ():
return Urlopen (URL). Read ()
return get
Content=index (' http://baidu.com ')

# Print (content (). Decode (' Utf-8 '))
# Print (content.__closure__[0].cell_contents)
In fact, the closure function is more used in adorners,


Decorative Device
=====

###### Decorator: is a tool that can add functions to a function,

He can be any object that can be called, and the object being decorated can be any object that can be called.

###### Why use adorners:
1. Open closure principle: The modification is closed, the extension is open
2. In order to not modify the source code of the decorated object and the method of invocation, to add new features,

###### a simple example

Import time
def timmer (FUC):
def wrapper ():
Start_time = Time.time ()
FUC ()
Stop_time = Time.time ()
Print ("Run time is%s"% (Stop_time-start_time))
Return wrapper
@timmer
def index ():
Time.sleep (3)
Print (' Welcome to New World ')
Index ()
This would have been a function without statistics running time, but using adorners to add the previous,
And there is no modification to the original code.

###### Process Analysis

Index () This function is original, I need to add, a time function, so I wrote a closure function (the adorner is implemented with a closure function), 4
This function is to add a chronograph function,
def timmer (fuc): #这个地方必须接受一个值, and this value is a function.
def wrapper (): #这个地方的参数根据被装饰函数来添加, start running
Start_time = Time.time ()
FUC () #开始执行函数, the function being performed is the decorated function
Stop_time = Time.time ()
Print ("Run time is%s"% (Stop_time-start_time))
Return wrapper # #这个是返回的一个值, this value is the wrapper function + the scope above it.

def index ():
Time.sleep (3)
Print (' Welcom to New World!!!!!! ')

f = Timmer (index) # #这个时候返回的wrapper () + scope above, total memory address
F () can be executed
Results:
‘‘‘
Welcom to New World!!!!!!
Run Time is 3.008370876312256
‘‘‘
But to ensure that the call is index () and not other functions
Then the function is re-assigned, so that the operation, you will find the same as the original call, but at this time the index () is not the original definition of the function, but wrapper () + the entire value of the above scope
Add @ on index () to call it this way
Index=timmer (Index)
Index ()

###### function with return value

If you have a function that returns a value, it can be resolved,
def timmer (FUC):
def wrapper ():
Start_time = Time.time ()
Res=fuc () # # #在这里就接受好了.
Stop_time = Time.time ()
Print ("Run time is%s"% (Stop_time-start_time))
return Res # #然后返回去
Return wrapper
@timmer # #修饰一下
def index ():
Time.sleep (3)
Print (' Welcom to New World!!!!!! ')
Return 1 # #这里有个返回值.


###### Functions with parameters
Import time
def timmer (FUC):
def wrapper (*args,**kwargs): #在这里就传参数好了
Start_time = Time.time ()
FUC (*args,**kwargs) #当然在这里也得需要.
Stop_time = Time.time ()
Print ("Run time is%s"% (Stop_time-start_time))
Result Wrapper

def hompage (name):
Time.sleep (1)
Print (' Welcome to%s '% name)

###### Example

login_user={' user ': None, ' status ': False} # #这个是保存一个状态
def auth (func):
def wrapper (*args,**kwargs):
If login_user[' user '] and login_user[' status ']: # #这个是检查状态, if passed, returns the function directly.
# # does not make the following judgments. If you ask this, what's the use, when you
# #执行的时候就会发现, if you have, you have to enter it two times
res = func (*args,**kwargs)
return res
Else
Name = input (' Name: ')
PWD = input (' Password: ')
If name = = ' Liukang ' and pwd = = ' 123 ':
login_user[' user ']=name
login_user[' status ']=true
Res=func (*args,**kwargs)
return res
Else
Print (' auth failed ')
Return wrapper

# #底下是主页, now to add a certified feature.
@auth
def index ():
Print (' Welcome to index page ')
@auth
def home (name):
Print ('%s Welcome to Home page '%name)
Index ()
Home (' Liukang ') def ha ()


Iterator to the ###### function
Why Use iterations:
1. It can abstract the access logic from different types of collection classes, thus avoiding exposing the internal structure of the collection to the client.
2. For data types that do not have an index, you must provide an iterative approach that does not depend on the index
The concept of iteration:
Repeat + the result of the last iteration is the initial value of the next iteration, the repeating process is called an iteration, and each repetition is an iteration,
And the result of each iteration is the initial value of the next iteration
Advantages and disadvantages of iterators
Advantages:
1. Provides an iterative approach that does not rely on subscript
2. More memory savings on the drop iterator itself

Disadvantages:
1. Unable to get the length of the iterator object
2. The value of the sequence type is flexible, is a one-time, can only be taken back to the value, not forward


__iter__ methods are available for iterative objects
# [1,2].__iter__ ()
# ' Hello '. __iter__ ()
# ($). __ITER__ ()
#
# {' A ': 1, ' B ': 2}.__iter__ ()
# {1,2,3}.__iter__ ()


Iterator: Executes the __iter__ method, the result is the iterator, the iterator object has the __next__ method, this is the iterator
# i=[1,2,3].__iter__ ()
# Print (i)
# Print (i.__next__ ())
# Print (i.__next__ ())
# Print (i.__next__ ())
# Print (i.__next__ ()) #如果没有元素的话就抛出异常: stopiteration


How can I tell if an object is iterative?
From collections Import Iterable,iterator

# #以下是各个对象的测试
# ' abc '. __ITER__ ()
# (). __ITER__ ()
# [].__iter__ ()
# {' A ': 1}.__iter__ ()
# {1,2}.__iter__ ()
# f=open (' A.txt ', ' W ')
# f.__iter__ ()

#下列数据类型都是可迭代的对象
# Print (isinstance (' abc ', iterable))
# Print (Isinstance ([],iterable))
# Print (Isinstance ((), iterable))
# print (isinstance ({' A ': 1},iterable))
# print (isinstance ({1,2},iterable))
# Print (Isinstance (f,iterable))

But!!!
#只有文件是迭代器对象
# Print (isinstance (' abc ', Iterator))
# Print (Isinstance ([],iterator))
# Print (Isinstance ((), Iterator))
# print (isinstance ({' A ': 1},iterator))
# print (isinstance ({1,2},iterator))
# Print (Isinstance (f,iterator))

Iterate objects: Only the __iter__ method, the iterator object that the method gets executed

Iteration Protocol:
Object has __next__
The object is __iter__, and for an iterator object, the __iter__ method is executed, and the result is still itself

###### Generator
#生成器函数: As long as the function body contains the yield keyword, the function is the generator function
Generators are iterators

As the following example: This can only return a single value, if the return of all the words will have to trouble (without the premise of the generator)

# def foo ():
# return 1
# return 2
# return 3
# return 4
# Res1=foo ()
# Print (RES1)
# Res2=foo ()
# Print (Res2)

If so:

def foo ():
# print (' first ')
# yield 1
# print (' second ')
# yield 2
# print (' third ')
# yield 3
# print (' fourth ')
# yield 4
# print (' fifth ')
#
# G=foo ()
# for I in G:
# Print (i)

In fact, that's how it is done:

# Print (g)
# Print (Next (g)) #触发迭代器g的执行, which triggers the execution of the function, so the generator is an iterator
# Print (Next (g))
# Print (Next (g))
# Print (Next (g))
# Print (Next (g))

Yield Features:
1. The equivalent of encapsulating __iter__ and __next__ for functions
2.return can only return one value at a time, the function terminates,
Yield can return multiple values, each time a function is paused, and next next
The last paused position continues execution

Example: Simulating the function of Tail-f plus grep
#tail-F A.txt | grep ' python '

Import time
def tail (filepath):
With open (filepath,encoding= ' utf-8 ') as F:
F.seek (0,2)
While True:
Line=f.readline (). Strip ()
If line:
Yield line
Else
Time.sleep (0.2)
def grep (pattern,lines):
For line in lines:
If pattern in line:
Yield line
G=grep (' Python ', tail (' a.txt '))
Print (g)

For I in G:
Print (i)

###### #说明一下啊, this format is markdown format (even if the Mother egg file) but copied to this place will not be, you guys just look at it, have a question to say below. Built-in functions next time.

The path of the python's walking hole

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.