【ZZ已解决】Python中如何在嵌套函数内部访问被嵌套(的父级函数)中的(局部,非全局)变量...

本文介绍了在Python中如何从嵌套函数内部访问并修改其父级函数中的局部变量。对于Python 2.x版本,可以通过将变量放入列表来实现;而在Python 3.x中,则可以使用nonlocal关键字。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


之前就遇到这个问题了:


#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Function:
【已解决】Python中如何在嵌套函数内部访问被嵌套(的父级函数)中的(局部,非全局)变量
 
http://www.crifan.com/python_access_parent_nesting_function_local_variable_from_nested_function
 
Author:     Crifan Li
Version:    2012-12-25
Contact:    admin at crifan dot com
"""
 
def accessVarFromNestedFunc():
    localVarInParent = 1;
     
    def nestedFunc(): #
        localVarInParent = localVarInParent + 1 ;
        print "In nested func, localVarInParent=",localVarInParent;
     
    nestedFunc();
    print "In current parent nesting func, localVarInParent=",localVarInParent;
     
if __name__ == "__main__":
    accessVarFromNestedFunc();

即,在嵌套函数内部,操作,父级函数中的变量,但是对应的父级函数中该变量,只是个普通的局部变量。

但是结果会出错的:

D:\tmp\tmp_dev_root\python\access_var_from_nested_func>access_var_from_nested_func.py

Traceback (most recent call last):

  File "D:\tmp\tmp_dev_root\python\access_var_from_nested_func\access_var_from_nested_func.py", line 24, in <module>

    accessVarFromNestedFunc();

  File "D:\tmp\tmp_dev_root\python\access_var_from_nested_func\access_var_from_nested_func.py", line 20, in accessVarFromNestedFunc

    nestedFunc();

  File "D:\tmp\tmp_dev_root\python\access_var_from_nested_func\access_var_from_nested_func.py", line 17, in nestedFunc

    localVarInParent = localVarInParent + 1 ;

UnboundLocalError: local variable ‘localVarInParent’ referenced before assignment
但是一直也尝试过,写成global的形式,但是还是没法解决。

唯一可行的是,需要定义一个全局的变量才可以:

#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Function:
【已解决】Python中如何在嵌套函数内部访问被嵌套(的父级函数)中的(局部,非全局)变量
 
http://www.crifan.com/python_access_parent_nesting_function_local_variable_from_nested_function
 
Author:     Crifan Li
Version:    2012-12-25
Contact:    admin at crifan dot com
"""
 
localVarInParent = 1;
 
def accessVarFromNestedFunc():
 
    def nestedFunc(): #
        global localVarInParent;
        localVarInParent = localVarInParent + 1 ;
        print "In nested func, localVarInParent=",localVarInParent;
     
    nestedFunc();
    print "In current parent nesting func, localVarInParent=",localVarInParent;
     
if __name__ == "__main__":
    accessVarFromNestedFunc();
但是很明显,不是想要的效果。

不想要增加全局的变量,只想操作父级函数内的变量。





【解决过程】

1.后来终于看到一个正确的解释了:

How do I change nesting function’s variable in the nested function

针对Python 2.x,则可以改为:

#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Function:
【已解决】Python中如何在嵌套函数内部访问被嵌套(的父级函数)中的(局部,非全局)变量
 
http://www.crifan.com/python_access_parent_nesting_function_local_variable_from_nested_function
 
Author:     Crifan Li
Version:    2012-12-25
Contact:    admin at crifan dot com
"""
 
def accessVarFromNestedFunc():
    localVarInParent = [1]; #here just define a list, first value is what we want to use
     
    def nestedFunc(): #
        localVarInParent[0] = localVarInParent[0] + 1 ; # localVarInParent[0] is the first value of above list value: localVarInParent, and its initial value is 1
        print "In nested func, localVarInParent[0]=",localVarInParent[0];#2,3,4,5,6
     
    for i in range(5):
        nestedFunc();
    # here can got value is 6, which is changed after nested function
    print "In current parent nesting func, localVarInParent[0]=",localVarInParent[0]; #In current parent nesting func, localVarInParent[0]= 6
     
if __name__ == "__main__":
    accessVarFromNestedFunc();
针对Python 3.x,是可以添加对应的nonlocal的声明的。这个暂时不去折腾了,有空再试试。



【总结】

Python中,嵌套函数内部去操作被嵌套的父级函数中的变量的话:
Python 2.x:把变量弄进一个列表中的第1个值,index=0,然后就可以在嵌套函数中,获得该list列表变量,操作其中第1个值了。
Python 3.x:把变量定义为nonlocal即可。



转载于:https://my.oschina.net/u/1178546/blog/164224

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值