Python闭包中的陷阱

简介: Python闭包中的陷阱

Python闭包中的陷阱

**陷阱1**
def outer():
    local=10
    def inner():
        local+=10
        return local
    return inner
resu=outer()

"""变量local是介于局部变量与全局变量之间的一种变量,
   内层函数对其修改会报错,需要使用 nonlocal进行声明
"""
def outer():
    local=10
    def inner():
        nonlocal local
        local+=10
        return local
    return inner
fun=outer()
print(fun())
#陷阱2
def fun1():
    lst=[]
    for i in range(1,4):
        def fun2():
            return i**2
        lst.append(fun2)
    return lst
f1,f2,f3=fun1()
print(f1(),f2(),f3())
"""解决办法:使用局部变量接收参数1,"""
9 9 9
def fun3():
    lst=[]
    for i in range(1,4):
        def fun4(_i=i):
            return _i**2
        lst.append(fun4)
    return lst
f4,f5,f6=fun3()
print(f4(),f5(),f6())
1 4 9
相关文章
|
6月前
|
数据安全/隐私保护 Python
Python中装饰器、回调函数、闭包、派生的区别与应用详解
Python中装饰器、回调函数、闭包、派生的区别与应用详解
67 0
|
7月前
|
存储 自然语言处理 Python
Python闭包(Python Closures)介绍
介绍python的闭包语法。
50 0
Python闭包(Python Closures)介绍
|
23天前
|
人工智能 机器人 测试技术
【python】python闭包的详细解读(傻瓜式教学)
【python】python闭包的详细解读(傻瓜式教学)
|
1月前
|
存储 程序员 Python
Python教程第9章 | 通俗易懂学闭包
本文通过一个需求探讨闭包的基本概念与用法,帮助快速理解闭包。
14 0
|
2月前
|
自然语言处理 安全 Python
Python中的闭包和高阶函数详解
Python中的闭包和高阶函数详解
|
2月前
|
Python
在Python中,如何创建和使用闭包?
在Python中,如何创建和使用闭包?
|
2月前
|
自然语言处理 Python
在Python中,什么是闭包?
在Python中,什么是闭包?
|
3月前
|
Python
Python学习 -- 高阶、闭包、回调、偏函数与装饰器探究
Python学习 -- 高阶、闭包、回调、偏函数与装饰器探究
20 0
|
8月前
|
Python
|
4月前
|
Python
Python 基础知识:解释 Python 的装饰器和函数闭包的关系。
Python 基础知识:解释 Python 的装饰器和函数闭包的关系。
25 0