当前位置 : 主页 > 编程语言 > python >

python 闭包

来源:互联网 收集:自由互联 发布时间:2021-06-25
#不是闭包 def f1(): a = 10 def f2(): a = 20 print (a) print (a) -- 10 f2() -- 20 print (a) --10 f1() ___ 闭包 def f1(): a = 10 def f2(): c = 20 * a return f2f = f1() print (f. __closure__ ) origin= 0 def factory(pos): def go(step): no

 

 

#不是闭包
def
f1(): a = 10 def f2(): a = 20 print(a) print(a) -- 10 f2() -- 20 print(a) --10 f1()

___

闭包

def f1():
    a = 10
    def f2():
        c = 20 * a
    return f2
f = f1()
print(f.__closure__)

origin=0

def factory(pos):
    def go(step):
        nonlocal pos 
        new_pos = pos + step
        pos = new_pos
        return new_pos
    return  go


t = factory(origin)
print(t(2))
--2
print(t(3))
--5
print(t(5))
--10print(origin)--0
网友评论