`
cnDenis
  • 浏览: 99226 次
  • 来自: 广州
社区版块
存档分类
最新评论

Python 3.x中的nonlocal及其在2.x中的变通办法

阅读更多

 

Python 3.x中的nonlocal及其在2.x中的变通办法

by cnDenis http://cndenis.iteye.com 2012年12月26日

在Python 2.x中,函数内部可以定义函数,内层的函数可以读取外层函数的局部变量,但却不可以修改它.

1
2
3
4
5
6
7
8
#!/usr/bin/python
def outter():
    x = 1
    def inner():
        print("inner is called, x=", x)
    return inner

outter()()

上面这个程序是没问题的,但是,下面这个就会出错:

1
2
3
4
5
6
7
8
9
#!/usr/bin/python
def outter():
    x = 1
    def inner():
        print("inner is called, x=", x)
        x = 2
    return inner

outter()()

提示竟然是UnboundLocalError: local variable 'x' referenced before assignment,找不到变量。

这个错误在Python 3.x中的解决方法是使用Py3k新增的关键词nonlocal

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#!/usr/bin/python
def outter():
    x = 1
    def inner():
        nonlocal x
        print("inner is called, x=", x)
        x = 2
    return inner

outter()()

但Python 2.x中没有这个关键词,怎么办呢?如果对变量的改变的不需要影响外层的话,可以新建一个变量来用也可以。

新建变量的方式:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#!/usr/bin/python
def outter():
    x = 1
    def inner():
        y = x
        print("inner is called, x=", y)
        y = 2
    return inner

outter()()

由于y是在内层函数中定义的,可以随便改变,但外层函数看不见y。而如果需要内层对变量的改变被外层看到的话,变通的方法是使用可变的对象,例如dict、对像的属性等。例如 Python 3.x中的代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#!/usr/bin/python
def outter():
    x = 1
    def inner():
        nonlocal x
        print("inner is called, x=", x)
        x = 2
    inner()
    print("outter after inner called, x=", x)

outter()

#Python 3.3中输出:
#inner is called, x= 1
#outter after inner called, x= 2

在Python 2.x中用dict的方式变通为:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#!/usr/bin/python
def outter():
    x = {}
    x[0] = 1
    def inner():
        print("inner is called, x=", x[0])
        x[0] = 2
    inner()
    print("outter after inner called, x=", x[0])

outter()
#Python 2.7中输出:
#inner is called, x= 1
#outter after inner called, x= 2

用对像的属性的方式:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#!/usr/bin/python
class C(object):
    pass

def outter():
    x = C()
    x.v = 1
    def inner():
        print("inner is called, x=", x.v)
        x.v = 2
    inner()
    print("outter after inner called, x=", x.v)

outter()
#Python 2.7中输出:
#inner is called, x= 1
#outter after inner called, x= 2

以上内容参考了:Python的闭包与nonlocal 以及 Simulating nonlocal in Python 2.x

 

0
4
分享到:
评论

相关推荐

    Python 084.nonlocal_global.mp4

    Python 084.nonlocal_global.mp4

    Python中关键字global和nonlocal的区别详解

    两个关键词都用于允许在一个局部作用域中使用外层的变量。 global 表示将变量声明为全局变量 nonlocal 表示将变量声明为外层变量(外层函数的局部变量,而且不能是全局变量) 注意:我使用的是Python3.6.3,可能和...

    Nonlocal_PBM.rar_Nonlocal-PBM

    Coupé P, Manjón J V, Fonov V, et al. Patch-based segmentation using expert priors: Application to hippocampus and ventricle segmentation

    NLMLPR_code.zip_Nonlocal means_denoising_image denoising_nonloca

    image denoising using nonlocal means algorithm for image denoising

    python关键字.pdf

    python关键字(简) >>> import keyword >>> keyword.kwlist ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', '...

    python3.6.5参考手册 chm

    The Future for Python 2.x Changes to the Handling of Deprecation Warnings Python 3.1 Features PEP 372: Adding an Ordered Dictionary to collections PEP 378: Format Specifier for Thousands Separator...

    Python中 Global和Nonlocal的用法详解

    global 语句中列出的名称不能定义为形式参数,也不能在 for 循环控制目标、 class 定义、函数定义、 import 语句或变量注释中定义。 当前的实现并不强制执行这些限制,但是程序不应该滥用这种自由,因为未

    python global和nonlocal用法解析

    这篇文章主要介绍了python global和nonlocal用法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 ◆global和nonlocal是Python的两个重要变量作用域关键字 ...

    Nonlocal Continuum Field Theories-Springer-Verlag New York (2004).pdf

    纳米力学经典图书,A. Cemal Eringen (eds.)-Nonlocal Continuum Field Theories-Springer-Verlag New York (2004).pdf

    Python之路V1.3.pdf

    Python 基础主要总结Python 常用内置函数;Python 独有的语法特性、关键词 nonlocal, global 等;内置数据结构包括:列表(list), 字典(dict), 集合(set), 元组(tuple) 以及相关的高级模块collections 中的Counter,...

    Python中关键字nonlocal和global的声明与解析

    主要给大家介绍了关于Python中关键字nonlocal和global的声明与解析的相关资料,文中介绍的非常详细,相信对大家具有一定的参考价值,需要的朋友们下面来一起看看吧。

    Python语言基础:global 和 nonlocal关键字.pptx

    当内部作用域想修改外部作用域的变量时,就需要用到global关键字。 实例:修改全局变量 num,并输出结果。 num = 1 def fun1(): global num # 需要使用 global 关键字声明 print(num) num = 123 ...

    Python基础语法.docx

    /usr/bin/python3 # -*- coding: UTF-8 -*- 2. 导入模块行 导入整个模块,格式: import module 导入模块中全部函数,格式为: from module import * 二、标识符 首字符必须是字母或下划线。 标识符对大小写敏感。 ...

    Python语言基础:作用域.pptx

    Python 中,变量的访问权限决定于这个变量是在哪里赋值的。变量的作用域决定了在哪一部分程序可以访问哪个特定的变量名称。Python的作用域一共有4种,分别是:L(Local):最内层,包含局部变量,比如一个函数/方法...

    Python程序基础:函数综合案例.pptx

    在Python中,每个Python文件都可以作为一个模块,模块的名字就是文件名。;Python提供了一个__name__属性,通过__name__属性可以识别程序的使用方式: 当作为模块导入时,则其__name__属性的值被自动设置为模块名; ...

    Python 闭包,函数分隔作用域,nonlocal声明非局部变量操作示例

    本文实例讲述了Python 闭包,函数分隔作用域,nonlocal声明非局部变量操作。分享给大家供大家参考,具体如下: 实例对象也可以实现闭包的功能,不过实例对象消耗的资源(内存)比闭包多。 demo.py(闭包): # 闭包,...

Global site tag (gtag.js) - Google Analytics