美文网首页
Python变量, 2023-03-20

Python变量, 2023-03-20

作者: Mc杰夫 | 来源:发表于2023-03-19 22:42 被阅读0次

    (2023.03.20 Mon)
    Python变量有四种作用域(scope),按覆盖范围从小到大依次是

    • local
    • enclosing
    • global
    • built-in

    Local scope
    创建于函数中的变量,只在函数范围内有效,而函数外使用时将无效。该变量属于函数的局部作用域(local scope)。
    Enclosing scope
    enclosing作用域发生在有嵌入式函数的场合。嵌入式函数至少有一个内部函数和外部函数(outside function)。当一个变量在外部函数中定义,则该变量在函数的enclosing作用域。在enclosing作用域的变量对内部函数和外部函数同时可见。
    例子

    def foo():
      scope = "enclosed"
      def func():
        print(scope)
      func()
    

    调用

    >> foo()
    enclosed
    

    这里我们引入一个关键字nonlocal,该关键字用于enclosing scope中内部函数修改enclosing变量使用。
    例子

    def out():
        a = 10
        def inside():
            nonlocal a
            print(f"enclosing variable in the internal function before update: {a}")
            a += 99
            print(f"enclosing variable in the internal function: {a}")
        inside()
        print(f"enclosing variable after update by nonlocal keyword: {a}")
    

    返回

    >> out()
    enclosing variable in the internal function before update: 10
    enclosing variable in the internal function: 109
    enclosing variable after update by nonlocal keyword: 109
    

    Global scope
    global variable在全局作用域(global scope)中声明(declare)的变量,可以被整个程序使用。可在函数作用域的内、外使用使用全局变量。典型的,全局变量在Python代码中、函数外声明。声明时可加入关键字global,也可不加。在函数中调用全局变量,不可修改,修改全局变量前需要声明该全局变量。
    例子

    name = "abc"
    def foo():
        print("Name inside foo() is ", name)
    foo()
    print("Name outside foo() is :", name)
    

    返回

    Name inside foo() is  abc
    Name outside foo() is : abc
    

    但是如果在函数内部修改调用的全局变量,则返回错误UnboundLocalError

    global x
    x = 5
    def test():
        x += 1
        return x
    

    调用

    >> test()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 2, in test
    UnboundLocalError: local variable 'x' referenced before assignment
    

    如果在修改前声明其为全局变量,则可以修改

    global x
    x = 5
    def test1():
        global x
        x += 1
        return x
    

    调用

    >> test1()
    6
    

    Built-in scope
    内置作用域是python中可用范围最广的作用域,包括关键词(keywords),函数,异常(exceptions),以及python内置的其他属性(attributes)。内置作用域中的名字在python代码中均可使用,他们在python程序/脚本运行时自动加载。
    例子

    >> id('a')
    140275629228912
    

    全局变量Global Variable

    全局变量可在函数外定义,是在函数内外都可访问的变量。

    需要注意的是,Python中全局变量的作用域为module内部/文件内部,即跨文件的全局变量无法互相访问(?)。互相访问可能会产生循环依赖问题(circular import)。

    解决方案是将全局变量保存在一个独立的文件中,caller从该文件中import,可避免circular import 问题。例,创建变量config.py用于保存全局变量

    # config.py
    a = 1
    b = 'string'
    

    在另一个Python脚本中调用全局变量

    # test.py
    import config
    print(config.a)
    print(config.b)
    

    运行

    >> python test.py
    1
    string
    

    Reference

    1 stackoverflow
    2 知乎
    `

    相关文章

      网友评论

          本文标题:Python变量, 2023-03-20

          本文链接:https://www.haomeiwen.com/subject/wnnyrdtx.html