美文网首页
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 知乎
`

相关文章

  • 1.1 python变量/输出/输入

    python版本:python 3.5.2注释符号:#发布时间:2018.10.26 一、变量 变量是什么? 变量...

  • Python变量和数据类型

    一. Python中的变量赋值 单变量赋值: 多变量赋值: 二. Python中的数据类型 Python有五个...

  • 第二章

    变量和简单类型 单行注释和多行注释 Python是弱类型语言 Python变量的特征 Python变量命名规则 P...

  • 2018-02-07

    python pickle模块:python变量及对象的序列化 1、pickle.dump 将python变量...

  • 3. python3语法

    python3变量 1 声明变量语法:标识符/变量名=变量值 2 变量的命名规范(1). 在 Python 里...

  • python vs. js 常用语法对比

    python vs. js 变量 pythonjavascript变量注释#''' '''///* */变量a =...

  • Python变量的存储

    Python变量的存储 在高级语言中,变量是对内存及其地址的抽象。 对于python而言,python的一切变量都...

  • 2023-03-20

  • 2. Python变量类型

    变量创建 Python中变量创建比较简单, 如:变量名 = 变量值 根据上面的内容可以得出,Python中变量的类...

  • 03 Python环境变量部署和包管理工具安装

    Python环境变量部署 我们安装完Python后会得到python.exe python脚本的环境变量pyt...

网友评论

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

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