python函数式编程——闭包

# 非闭包
def curve_pre():
    def curve():
        print('This is a function') 
    return curve
f = curve_pre()
f()

# 闭包 = 函数 + 环境变量
# 现场
def curve_pre():
    a = 25
    def curve(x):
        return a*x*x  
    return curve

a = 10
f = curve_pre()
print(f(2))
print(f.__closure__)
print(f.__closure__[0].cell_contents)

def f1():
    a = 10
    def f2():
        a = 20
        print(a)
    print(a)
    f2()
    print(a)

f1()
print(f.__closure__)

'''
旅行者
x, y

x = 0
3 result = 3
5 result = 8
6 result = 14
'''
# 非闭包方法
origin = 0
def go(step):
    global origin
    nwe_pos = origin + step
    origin = nwe_pos
    return nwe_pos

print(go(2))
print(go(5))
print(go(8))

# 闭包实现方法 函数式编程
origin = 0
def factory(pos):
    def go(step):
        nonlocal pos
        nwe_pos = pos + step
        pos = nwe_pos
        return nwe_pos
    return go

tourist = factory(origin)
print(tourist(2))
print(tourist.__closure__[0].cell_contents)
print(tourist(5))
print(tourist.__closure__[0].cell_contents)
print(tourist(8))

函数式编程

闭包

In [19]:
# 非闭包
def curve_pre():
    def curve():
        print('This is a function') 
    return curve
f = curve_pre()
f()
This is a function
In [24]:
# 闭包 = 函数 + 环境变量
# 现场
def curve_pre():
    a = 25
    def curve(x):
        return a*x*x  
    return curve
a = 10
f = curve_pre()
print(f(2))
print(f.__closure__)
print(f.__closure__[0].cell_contents)
100
(<cell at 0x0000000005CC01F8: int object at 0x0000000077FB63A0>,)
25
In [26]:
 
           
def f1():
    a = 10
    def f2():
        a = 20
        print(a)
    print(a)
    f2()
    print(a)
f1()
print(f.__closure__)
10
20
10
(<cell at 0x0000000005CC01F8: int object at 0x0000000077FB63A0>,)
In [47]:
 
           
'''
旅行者
x, y
x = 0
3 result = 3
5 result = 8
6 result = 14
'''
Out[47]:
1
In [56]:
 
           
# 非闭包方法
origin = 0
def go(step):
    global origin
    nwe_pos = origin + step
    origin = nwe_pos
    return nwe_pos
print(go(2))
print(go(5))
print(go(8))
2
7
15
In [65]:
# 闭包实现方法 函数式编程
origin = 0
def factory(pos):
    def go(step):
        nonlocal pos
        nwe_pos = pos + step
        pos = nwe_pos
        return nwe_pos
    return go
tourist = factory(origin)
print(tourist(2))
print(tourist.__closure__[0].cell_contents)
print(tourist(5))
print(tourist.__closure__[0].cell_contents)
print(tourist(8))
2
2
7
7
15
In [ ]:

猜你喜欢

转载自blog.csdn.net/weixin_40327641/article/details/80159002