Foundations and python callback function returns the closure

??? a callback function

The callback function is a function call through a function pointer, if you put another argument pointer (address) function is passed as a parameter, when the pointer is used to call the function it points to, which is what we call a callback function .

In simple terms: the callback function is to function as a parameter passed to the function.

Requirements: now offers free wake-up service, there are several ways wake up, you can choose, such as serial killer phone call, or a head-cold water splashed up early, as you yourself like, as long as you make reservations in advance, the hotel work It will wake you up with the way you like in your specified time.

def  wake_call(time):
    #第一种叫醒服务
    print(time,"使用夺命电话连环call叫醒主人")

def wake_water(time):
    #第二种叫醒服务
    print(time,"使用早起泼冷水的方式叫醒主人")

def call_wake(time, func_name):
    # 这个很重要,这个就是酒店服务业务的系统业务
    #这是实现回调函数的核心
    # time :预约时间
    # func_time:回调函数名
    # return :调用的函数的结果
    return func_name(time)

#调用函数
#wake_call 被调用的函数就是回调函数
call_wake("凌晨7点", wake_call)

Expansion : Programming divided into two categories: system programming and application programming, so-called system programming is simply to write library, application programming is the use of the various libraries written to write some specific features of the program, which is the application the system programmers will leave API (application programming Interface) in write their own library for use by programmers.

When the program is run, under normal circumstances, the application often through API calls function library had prepared good, but some library functions but requires the application give it a transfer function, and good call right time to complete the goal, this function is passed later was called to become the callback function

Two return function

Function as a return value

In addition to receiving the python as a function of parameters, also as a function of the result value is returned.

Requirements: variable parameters to achieve a sum usually so defined:

def calc_sum(*args):
    sum = 0
    for i in args:
        sum += i
    return sum

Now the demand has changed, and now I do not need sum immediately, but later in your code, as required, and then calculated, this time, we can not return the results of summation, but return function sum.

def lazy_sum(*args):
    def calc_sum():
        sum = 0
        for i in args:
            sum += i
        return sum
    return calc_sum

When we call lazy_sum (), the results are not returned but the sum of the sum function

>>> f = lazy_sum(1, 2, 3, 4)
>>> f
<function lazy_sum.<locals>.calc_sum at 0x101b61598>

This time when you call f, really summation of results

>>> f()
10

Like the above function, we function lazy_sum are also defined function calc_sum, and the internal functions calc_sum use lazy_sum parameters and local variables, when lazy_sum return function calc_sum, related parameters and variables are stored in returned by the function, which species known as "closure"

Note: When we call lazy_sum (), each call will return a new function, even if the same parameters passed.

Three closures

If another function is defined within a function, let's call outside the external functions, the function call inside

Closure: defines an internal function, the function in use of temporary variables outside the function in a function outside, and outside the function returns a reference to the function value, this constitutes a closure

In general, if a function ends, all the stuff inside function will be freed, returned to memory, local variables will disappear, but the closure is a special case, if the outer function found at the end of its own temporary variables will be used in future internal variables, put the temporary variable is bound to the inner function, and then ended his own.

#外函数, a与b都是临时变量
def outer(a):
    b = 10
    #内函数
    def inner():
        #在内函数中用到了外函数的临时变量
        print(a+b)
    #外函数的返回值是内函数的引用
    return inner
# 调用函数传入参数5
f = outer(5)
f()
#结果
15

Access something outside the function within the function. Closures also has the role of improving the code reusability. Closure effectively reduces the number of parameters needed to define the function

Four recursive function

Recursive function : inside the function, you can call other functions, if a function calls itself within itself, this function is a recursive function.

Recursive call : a function calls itself, has become a recursive function

Demand: calculating n = 1x2x3x4x ... x (n-1) xn!

Recursive ideas to solve problems

method:

1. Write a critical condition

2. This is a time to look for relationships and on

3. Assuming the current function has been able to call itself a result of the calculation, then calculated the results of this

# 关系: n!= (n-1)!xn
def fact(n):
    #临界条件
    if n==1:
        return 1
    #返回本次的调用结果
    return n*fact(n-1)

Advantage is to define a simple recursive function, logical, theoretically all recursive functions can be written in a cyclic manner, but not as a recursive loop logic clear.

Note: Note recursive function is used to prevent a stack overflow, in the function computer through the stack (Stack) to achieve this data structure, each time a function call to enter, will increase the layer stack frames, each time the function returns, to the stack will be reduced by one stack frame, stack size is unlimited, so when the number of calls too much time, will cause a stack overflow

Seeking Fibonacci columns: 1,1,2,3,5,8,13,21,34,55,89 ... ..
requirements: a report number, direct access to value this position

#关系 第n个位置上的数值=(n-1)+(n-2)
#临界值 第一个位置和第二个位置的值为1
def func1(n):
    if n==1 or n==2:
        #临界值
        return 1
    else:
        #返回本次调用的结果
        return func1(n-1) + func1(n-2)

Exercise enter a number from the console input, recursive summation.

Five os module

In automated testing, often need to find the file operations, such as finding the configuration file (and thus reads the information of the configuration file), to find test reports, etc., often have a large number of files and directories operation, which relies os module

1. os.getcwd()

Features: View current path

import os
print(os.getcwd())

2. os.listdir ()

All files in the directory list, returns a list of types

import os
print(os.listdir("c:\file"))

3. os.path.abspath(path)

Function: Returns the path absolute path

import os
print(os.path.abspath("."))

4. os.path.split(path)

Function: decomposition path (folder, file name), it returns a tuple

Note: If the last character in the string is a path, then only the folder section has a value, if no path string, the only part of the file name has value, if there is a path string \ and not in the end, the folders and files name has value, and returns the results do not include \

import os
print(os.path.split(r"D:\python\file\hello.py"))
#结果
('D:\python\file','hello.py')

print(os.path.split("."))
#结果
('','.')

os.path.split('D:\\pythontest\\ostest\\')
#结果
('D:\\pythontest\\ostest', '')

os.path.split('D:\\pythontest\\ostest')
('D:\\pythontest', 'ostest')

5. os.path.join(path1,path2,…)

The path combined, if one has an absolute path, the path will be deleted before.

>>> import os
>>> os.path.join(r"d:\python\test",'hello.py')
'd:\pyhton\test\hello.py'
>>> os.path.join(r"d:\pyhton\test\hello.py",r"d:\pyhton\test\hello2.py")
'd:\pyhton\test\hello2.py'

6. os.path.dirname(path)

Return path folder section, does not include the "\"

>>> import os
>>> os.path.dirname(r"d:\pyhton\test\hello.py")
'd:\pyhton\test'
>>> os.path.dirname(".")
''
>>> os.path.dirname(r"d:\pyhton\test\")
'd:\pyhton\test'
>>> os.path.dirname(r"d:\pyhton\test")
test

7. os.path.basename(path)

Function: Returns the file name path

>>> import os
>>> os.path.basename(r"d:\pyhton\test\hello.py")
'hello.py'
>>> os.path.basename(".")
'.'
>>> os.path.basename(r"d:\pyhton\test\")
''
>>> os.path.basename(r"d:\pyhton\test")
'test'

8. os.path.getsize(path)

Function: Gets the size of the file, folder if it returns 0

>>> import os
>>> os.path.getsize(r"d:\pyhton\test\hello.py")
38L
>>> os.path.getsize(r"d:\pyhton\test")
0L

9. os.path.exists(path)

>>> import os
>>> os.listdir(os.getcwd())
['hello.py','test.txt']
>>> os.path.exists(r"d:\python\test\hello.py")
True
>>> os.path.exists(r"d:\python\test\hello1.py")
False

Five stacks and queues

5.1 stack stack

Features: FIFO [can be abstracted into beans, advanced after going out of bamboo] latecomers


mystack = []
#压栈[向栈中存数据]
mystack.append(1)
print(mystack)
mystack.append(2)
print(mystack)
mystack.append(3)
print(mystack)

#出栈[从栈中取数据]
mystack.pop()
print(mystack)
mystack.pop()
print(mystack)
5.2 queue queue

Features: FIFO [laid flat can be abstracted into a water]

#导入数据结构的集合
import collections
queue = collections.deque([1, 2, 3, 4, 5])
print(queue)

#入队[存数据]
queue.append(8)
print(queue)
queue.append(9)
print(queue)

#取数据
print(queue.popleft())
print(queue)

Six directory traversal

6.1 Recursive directory traversal
import os

def getall(path, treeshow):
    filelist = os.listdir(path)
    treeshow += "   "
    for filename in filelist:
        #拼接绝对路径
        filepath = os.path.join(path, filename)
        if os.path.isdir(filepath):
            print(treeshow,"目录",filename)
            getall(filepath, treeshow)
        else:
            print(treeshow,"文件",filename)
getall(r"d:\python\test","")
6.2 Stack simulation recursive directory traversal

Also known as deep traversal

Draw analysis:

Depth traversal

import os

def getAllDirDE(path):
    stack = []
    stack.append(path)
    #处理栈,当栈为空的时候结束循环
    while len(stack) != 0:
        #从栈里取出数据
        dirPath = stack.pop()
        #目录下所有文件
        fileList = os.listdir(dirPath)
        for fileName in fileList:
            fileAbsPath = os.path.join(dirPath,fileName)
            if os.path.isdir(fileAbsPath):
                #是目录就压栈
                print("目录:", fileName)
                stack.append(fileAbsPath)
            else:
                #打印普通文件
                print("普通文件:", fileName)
getAllDirED(r"/Users/zhangjiao/PycharmProjects/teaching")
6.3 queue simulation recursive directory traversal

Also known as the breadth traversal

Draw analysis:

Breadth traversal

import os
import collections
def getAllDirQU(path):
    queue = collections.deque()
    #进队
    queue.append(path)
    while len(queue) != 0:
        #出队数据
        dirPath = queue.popleft()
        #找出所有的文件
        fileList = os.listdir(dirPath)
        for fileName in fileList:
            #绝对路径
            fileAbsPath = os.path.join(dirPath, fileName)
            #判断是否是目录,是目录就进队,不是就打印
            if os.path.isdir(fileAbsPath):
                print("目录:", fileName)
                queue.append(fileAbsPath)
            else:
                print("普通文件:", fileName)
getAllDirQU(r"/Users/zhangjiao/PycharmProjects/teaching")
Published 31 original articles · won praise 4 · Views 3517

Guess you like

Origin blog.csdn.net/qq_29074261/article/details/80016788