- Python 基础知识
 - Python - 主页
 - Python - 概述
 - Python - 历史
 - Python - 特性
 - Python 与 C++
 - Python——Hello World 程序
 - Python - 应用领域
 - Python解释器
 - Python-环境设置
 - Python-虚拟环境
 - Python - 基本语法
 - Python - 变量
 - Python - 数据类型
 - Python - 类型转换
 - Python - Unicode 系统
 - Python - 文字
 - Python - 运算符
 - Python - 运算符优先级
 - Python - 算术运算符
 - Python - 赋值运算符
 - Python - 增强运算符
 - Python - 比较运算符
 - Python - 逻辑运算符
 - Python - 位运算符
 - Python - 会员运算符
 - Python - 身份运算符
 - Python - 注释
 - Python - 用户输入
 - Python - 数字
 - Python - 布尔值
 - Python 控制语句
 - Python - 控制流
 - Python - 决策
 - Python - 如果有的话
 - Python - 大小写匹配语句
 - Python - for 循环
 - Python - for-else 循环
 - Python - While 循环
 - Python-break语句
 - Python-继续语句
 - Python - pass 语句
 - Python 函数和模块
 - Python - 函数
 - Python - 默认参数
 - Python - 关键字参数
 - Python - 仅关键字参数
 - Python - 位置参数
 - Python - 仅位置参数
 - Python - 任意参数
 - Python - 变量作用域
 - Python - 函数注释
 - Python - 模块
 - Python - 内置函数
 - Python 字符串
 - Python-字符串
 - Python - 字符串切片
 - Python-修改字符串
 - Python-字符串连接
 - Python——字符串格式化
 - Python - 转义字符
 - Python - 字符串方法
 - Python - 弦乐练习
 - Python 列表
 - Python - 列表
 - Python - 访问列表项
 - Python - 更改列表项
 - Python - 添加列表项
 - Python - 删除列表项
 - Python - 循环列表
 - Python - 列表理解
 - Python - 列表排序
 - Python - 复制列表
 - Python - 连接列表
 - Python - 列表方法
 - Python - 列出练习
 - Python 元组
 - Python - 元组
 - Python - 访问元组项
 - Python - 更新元组
 - Python - 解压元组
 - Python - 循环元组
 - Python - 连接元组
 - Python - 元组方法
 - Python - 元组练习
 - Python 集
 - Python - 集合
 - Python - 访问设置项
 - Python - 添加设置项
 - Python - 删除设置项
 - Python - 循环集
 - Python - 连接集
 - Python - 复制集
 - Python - 集合运算符
 - Python - 设置方法
 - Python - 设置练习
 - Python 字典
 - Python - 字典
 - Python - 访问字典项目
 - Python - 更改字典项目
 - Python - 添加字典项
 - Python - 删除字典项
 - Python - 字典查看对象
 - Python - 循环字典
 - Python - 复制字典
 - Python - 嵌套字典
 - Python - 字典方法
 - Python - 字典练习
 - Python 数组
 - Python-数组
 - Python - 访问数组项
 - Python - 添加数组项
 - Python - 删除数组项
 - Python - 循环数组
 - Python - 复制数组
 - Python - 反转数组
 - Python - 数组排序
 - Python - 连接数组
 - Python - 数组方法
 - Python - 数组练习
 - Python 文件处理
 - Python - 文件处理
 - Python-写入文件
 - Python-读取文件
 - Python - 重命名和删除文件
 - Python - 目录
 - Python - 文件方法
 - Python - 操作系统文件/目录方法
 - 面向对象编程
 - Python - OOP 概念
 - Python - 对象和类
 - Python - 类属性
 - Python - 类方法
 - Python - 静态方法
 - Python - 构造函数
 - Python - 访问修饰符
 - Python——继承
 - Python——多态性
 - Python - 方法重写
 - Python - 方法重载
 - Python - 动态绑定
 - Python - 动态类型
 - Python - 抽象
 - Python-封装
 - Python - 接口
 - Python - 包
 - Python - 内部类
 - Python - 匿名类和对象
 - Python-单例类
 - Python - 包装类
 - Python-枚举
 - Python-反射
 - Python 错误与异常
 - Python - 语法错误
 - Python - 异常
 - Python - try- except 块
 - Python - try-finally 块
 - Python - 引发异常
 - Python - 异常链
 - Python - 嵌套 try 块
 - Python - 用户定义的异常
 - Python-日志记录
 - Python-断言
 - Python - 内置异常
 - Python 多线程
 - Python-多线程
 - Python-线程生命周期
 - Python - 创建线程
 - Python - 启动线程
 - Python - 连接线程
 - Python - 命名线程
 - Python-线程调度
 - Python-线程池
 - Python - 主线程
 - Python-线程优先级
 - Python - 守护线程
 - Python - 同步线程
 - Python同步
 - Python-线程间通信
 - Python-线程死锁
 - Python - 中断线程
 - Python 网络
 - Python-网络
 - Python-套接字编程
 - Python-URL 处理
 - Python - 泛型
 - Python 杂项
 - Python - 日期和时间
 - Python - 数学
 - Python - 迭代器
 - Python - 生成器
 - Python - 闭包
 - Python - 装饰器
 - Python - 递归
 - Python - 正则表达式
 - Python-PIP
 - Python-数据库访问
 - Python - 弱引用
 - Python-序列化
 - Python - 模板
 - Python - 输出格式
 - Python-性能测量
 - Python-数据压缩
 - Python - CGI 编程
 - Python - XML 处理
 - Python - 图形用户界面编程
 - Python - 命令行参数
 - Python - 文档字符串
 - Python-JSON
 - Python-发送电子邮件
 - Python - 进一步扩展
 - Python - 工具/实用程序
 - Python - 图形用户界面
 - Python 问题与解答
 - Python - 编程示例
 - Python - 快速指南
 - Python - 有用的资源
 - Python - 讨论
 
Python - 变量作用域
Python 变量作用域
Python 中的变量是计算机内存中对象的符号名称。Python 利用命名空间的概念来定义各种标识符(例如函数、变量等)的上下文。命名空间是在当前上下文中定义的符号名称的集合。
Python 提供以下类型的命名空间 -
内置命名空间包含内置函数和内置异常。Python 解释器加载后,它们就会被加载到内存中,并一直保留到解释器运Behave止。
全局命名空间包含主程序中定义的任何名称。这些名称保留在内存中,直到程序运行。
本地命名空间包含函数内部定义的名称。它们在函数运行之前一直可用。
这些名称空间相互嵌套。下图显示了命名空间之间的关系。
某个变量的生命周期仅限于定义它的名称空间。因此,无法从任何外部命名空间访问内部命名空间中存在的变量。
Python globals() 函数
Python 的标准库包含一个内置函数globals()。它返回全局命名空间中当前可用的符号字典。
直接从 Python 提示符运行 globals() 函数。
>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>}
可以看到,包含所有内置函数和内置异常定义的builtins模块已被加载。
保存以下包含几个变量的代码和一个内部包含更多变量的函数。
name = 'TutorialsPoint' marks = 50 result = True def myfunction(): a = 10 b = 20 return a+b print (globals())
从该脚本内部调用 globals() 返回以下字典对象 -
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x00000263E7255250>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:\\Users\\user\\examples\\main.py', '__cached__': None, 'name': 'TutorialsPoint', 'marks': 50, 'result': True, 'myfunction': <function myfunction at 0x00000263E72004A0>}
全局命名空间现在包含程序中的变量及其值以及其中的函数对象(而不是函数中的变量)。
在函数外部创建的任何变量都可以在任何函数内访问,因此它们具有全局作用域。下面是一个例子来展示Python中全局变量的用法:
x = 5 y = 10 def sum(): sum = x + y return sum print(sum())
这将产生以下结果:
15
Python locals() 函数
Python 的标准库包含一个内置函数locals()。它返回函数的本地命名空间中当前可用的符号字典。
修改上面的脚本以从函数内打印全局和本地命名空间的字典。
name = 'TutorialsPoint'
marks = 50
result = True
def myfunction():
   a = 10
   b = 20
   c = a+b
   print ("globals():", globals())
   print ("locals():", locals())
   return c
myfunction()
输出显示locals() 返回变量及其当前在函数中可用的值的字典。
globals(): {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x00000169AE265250>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'C:\\Users\\mlath\\examples\\main.py', '__cached__': None, 'name': 'TutorialsPoint', 'marks': 50, 'result': True, 'myfunction': <function myfunction at 0x00000169AE2104A0>}
locals(): {'a': 10, 'b': 20, 'c': 30}
由于 globals() 和 locals 函数都返回字典,因此您可以使用字典 get() 方法或索引运算符从各自的命名空间访问变量的值。
print (globals()['name']) # displays TutorialsPoint
print (locals().get('a')) # displays 10
下面是一个简单的例子来展示Python中局部变量的用法:
def sum(x,y): sum = x + y return sum print(sum(5, 10))
15
Python 中的命名空间冲突
如果全局和局部作用域中都存在同名变量,Python 解释器会优先考虑局部命名空间中的变量。
marks = 50 # this is a global variable def myfunction(): marks = 70 # this is a local variable print (marks) myfunction() print (marks) # prints global value
它将产生以下输出-
70 50
如果您尝试从函数内部操作全局变量的值,Python 会引发UnboundLocalError。
marks = 50 # this is a global variable def myfunction(): marks = marks + 20 print (marks) myfunction() print (marks) # prints global value
它将产生以下输出-
   marks = marks + 20
           ^^^^^
UnboundLocalError: cannot access local variable 'marks' where it is not associated with a value
要修改全局变量,您可以使用字典语法更新它,或者在修改之前使用global关键字引用它。
var1 = 50 # this is a global variable
var2 = 60 # this is a global variable
def myfunction():
   "Change values of global variables"
   globals()['var1'] = globals()['var1']+10
   global var2
   var2 = var2 + 20
myfunction()
print ("var1:",var1, "var2:",var2) #shows global variables with changed values
它将产生以下输出-
var1: 60 var2: 80
最后,如果您尝试访问全局范围内的局部变量,Python 会引发 NameError,因为局部范围内的变量无法在其外部访问。
var1 = 50 # this is a global variable
var2 = 60 # this is a global variable
def myfunction(x, y):
   total = x+y
   print ("Total is a local variable: ", total)
myfunction(var1, var2)
print (total) # This gives NameError
它将产生以下输出 -
Total is a local variable: 110
Traceback (most recent call last):
   File "C:\Users\user\examples\main.py", line 9, in <module>
   print (total) # This gives NameError
          ^^^^^
NameError: name 'total' is not defined