代码之家  ›  专栏  ›  技术社区  ›  mikemaccana

为什么我的函数不能访问封闭函数中的变量?

  •  1
  • mikemaccana  · 技术社区  · 15 年前

    我知道立法会的规则。但是,对函数是否具有对封闭函数中定义的变量的读取访问权的简单测试似乎实际上不起作用。Ie:

    #!/usr/bin/env python2.4
    '''Simple test of Python scoping rules'''
    
    def myfunction():
        print 'Hope this works: '+myvariable
    
    def enclosing():
        myvariable = 'ooh this worked'
        myfunction()
    
    if __name__ == '__main__':
        enclosing()
    

    返回:

    NameError: global name 'myvariable' is not defined
    

    我做错什么了吗?是否有比立法会决议令更多的内容?

    1 回复  |  直到 15 年前
        1
  •  2
  •   Terence Honles    15 年前

    你可以。。。

    如果你这样做:

    #!/usr/bin/env python2.4
    '''Simple test of Python scoping rules'''
    
    def enclosing():
        myvariable = 'ooh this worked'
    
        def myfunction():
             print 'Hope this works: ' + myvariable
    
        myfunction()
    
    if __name__ == '__main__':
        enclosing()
    

    …否则,您的函数不知道在哪里查找(它确实查找,但它查找全局变量,这就是为什么您得到错误的原因)(如果不能将函数定义为 嵌套的 函数

    推荐文章