Function objects closure

Function objects closure

Refers to the function object can be treated as a function of "" Data "" to handle

1. The function may be referenced

>>> def add(x, y):
...     return x+y
...
>>> func = add
>>> func(1, 2)
3

2. The transfer function can be used as parameters

>>> def foo(x,y,func):
...     return func(x,y)
...
>>> foo(1,2,add)
3

3. The function can be used as the return value

(Parameter passing time must not be bracketed, on the implementation of the brackets on the spot)

def index():
    print("from index")

def func(a):
    return a

a = func(index)
a()

4. The container type function may be used as an element

def func():
    print('from func')


l1 = [1, '2', func, func()]

f = l1[2]
print(f)
from func
<function func at 0x000001F6BD7F3E18>

Nested functions

Nested function calls: call functions within the function

definition:

Let the inner function closed, to prevent direct external call

effect:

The complex and a small function inside the function call, clear code structure to solve the problem

def index():
    def home():
        print("from home")
    home()

index()
from home

example:

def func1(x, y):
    if x > y:
        return x
    else:
        return y


print(func1(1,2))

def func2(x, y, z, a):
    result = func1(x, y)
    result = func1(result, z)
    result = func1(result, a)
    return result


print(func2(1, 200000, 3, 1000
2
200000

Closure function

Closed: internal functions on behalf of

Package: Reference "wrapped" with the outer layer outside the scope of the representative function

Is nested functions, function objects, and the scope of the name space binding body

1. closure function must be defined inside the function

2. The closure function name of the function can refer to the outer layer

Closure function is to prepare decorator

x = 1

def f1():
    def f2():
        print(x)
    return f2

def f3():
    x = 3
    f2 = f1()   #调用f1()返回函数f2
    f2()    #需要按照函数定义时的作用关系去执行,与调用位置无关
f3()
1

There are two ways for the transfer function of the value thereof, the value of one is directly passed as parameters, another is a function of the value of the packet

import requests


def get(url):       #第一种方式
    return requests.get(url).text


print(len(get('https://www.baidu.com')))
print(len(get('https://www.python.org')))
2443
49559

When downloading a way to repeat the same page of incoming url

import requests

def page(url):      #第二种方式
    def get():
        return requests.get(url).text
    return get


python = page('https://www.python.org')
python()

Way two need to pass a value, you'll get closure function that contains the specified url, and after calling the closure function without having to re-transmission url

Guess you like

Origin www.cnblogs.com/YGZICO/p/11843844.html