Python变量作用域(通俗易懂)

本文介绍了Python中的四种作用域:局部、闭包外的函数、全局和内置作用域。变量查找顺序遵循LEGB规则,示例展示了如何在不同作用域中定义和访问变量,包括使用`global`和`nonlocal`关键字。了解这些基础知识对于Python开发者至关重要。

Python 中变量的访问权限取决于其赋值的位置,这个位置被称为变量的作用域。Python 的作用域共有四种,分别是:局部作用域(Local,简写为 L)、作用于闭包函数外的函数中的作用域(Enclosing,简写为 E)、全局作用域(Global,简写为 G)和内置作用域(即内置函数所在模块的范围,Built-in,简写为 B)。

变量在作用域中查找的顺序是 L→E→G→B,即当在局部找不到时会去局部外的局部找(例如闭包),再找不到会在全局范围内找,最后去内置函数所在模块的范围中找。

分别在 L、E、G 范围内定义的变量的例子如下:
global_var = 0 #全局作用域
def outer():
enclosing_var = 1 #闭包函数外的函数中
def inner():
local_var = 2 #局部作用域

内置作用域则是通过 builtins 模块实现的,可以使用以下代码查看当前 Python 版本的预定义变量:
import builtins
dir(builtins)
上述代码的运行结果如下所示:

import builtins
dir(builtins)
[‘ArithmeticError’, ‘AssertionError’, ‘AttributeError’, ‘BaseException’, ‘BlockingIOError’, ‘BrokenPipeError’, ‘BufferError’, ‘BytesWarning’, ‘ChildProcessError’, ‘ConnectionAbortedError’, ‘ConnectionError’, ‘ConnectionRefusedError’, ‘ConnectionResetError’, ‘DeprecationWarning’, ‘EOFError’, ‘Ellipsis’, ‘EnvironmentError’, ‘Exception’, ‘False’, ‘FileExistsError’, ‘FileNotFoundError’, ‘FloatingPointError’, ‘FutureWarning’, ‘GeneratorExit’, ‘IOError’, ‘ImportError’, ‘ImportWarning’, ‘IndentationError’, ‘IndexError’, ‘InterruptedError’, ‘IsADirectoryError’, ‘KeyError’, ‘KeyboardInterrupt’, ‘LookupError’, ‘MemoryError’, ‘ModuleNotFoundError’, ‘NameError’, ‘None’, ‘NotADirectoryError’, ‘NotImplemented’, ‘NotImplementedError’, ‘OSError’, ‘OverflowError’, ‘PendingDeprecationWarning’, ‘PermissionError’, ‘ProcessLookupError’, ‘RecursionError’, ‘ReferenceError’, ‘ResourceWarning’, ‘RuntimeError’, ‘RuntimeWarning’, ‘StopAsyncIteration’, ‘StopIteration’, ‘SyntaxError’, ‘SyntaxWarning’, ‘SystemError’, ‘SystemExit’, ‘TabError’, ‘TimeoutError’, ‘True’, ‘TypeError’, ‘UnboundLocalError’, ‘UnicodeDecodeError’, ‘UnicodeEncodeError’, ‘UnicodeError’, ‘UnicodeTranslateError’, ‘UnicodeWarning’, ‘UserWarning’, ‘ValueError’, ‘Warning’, ‘WindowsError’, ‘ZeroDivisionError’, ‘build_class’, ‘debug’, ‘doc’, ‘import’, ‘loader’, ‘name’, ‘package’, ‘spec’, ‘abs’, ‘all’, ‘any’, ‘ascii’, ‘bin’, ‘bool’, ‘breakpoint’, ‘bytearray’, ‘bytes’, ‘callable’, ‘chr’, ‘classmethod’, ‘compile’, ‘complex’, ‘copyright’, ‘credits’, ‘delattr’, ‘dict’, ‘dir’, ‘divmod’, ‘enumerate’, ‘eval’, ‘exec’, ‘exit’, ‘filter’, ‘float’, ‘format’, ‘frozenset’, ‘getattr’, ‘globals’, ‘hasattr’, ‘hash’, ‘help’, ‘hex’, ‘id’, ‘input’, ‘int’, ‘isinstance’, ‘issubclass’, ‘iter’, ‘len’, ‘license’, ‘list’, ‘locals’, ‘map’, ‘max’, ‘memoryview’, ‘min’, ‘next’, ‘object’, ‘oct’, ‘open’, ‘ord’, ‘pow’, ‘print’, ‘property’, ‘quit’, ‘range’, ‘repr’, ‘reversed’, ‘round’, ‘set’, ‘setattr’, ‘slice’, ‘sorted’, ‘staticmethod’, ‘str’, ‘sum’, ‘super’, ‘tuple’, ‘type’, ‘vars’, ‘zip’]

定义在函数内部的变量拥有一个局部作用域,定义在函数外的变量拥有全局作用域。局部变量只能在其声明语句所在的函数内部访问,全局变量可以在整个程序范围内访问。调用函数时,所有在函数内声明的变量名称都将被加入到作用域中。对于新手小白想更轻松的学好Python基础,Python爬虫,web开发、大数据,数据分析,人工智能等技术,这里给大家分享系统教学资源,架下我尉(同英): 2763177065 【教程/工具/方法/解疑】

当内部作用域想修改外部作用域的变量时,需要使用 global 和 nonlocal 关键字声明外部作用域的变量,例如:
global_num = 1
def func1():
enclosing_num = 2
global global_num #使用global关键字声明
print(global_num)
global_num = 123
print(global_num)
def func2():
nonlocal enclosing_num
print(enclosing_num) #使用nonlocal关键字声明
enclosing_num = 456
func2 ()
print(enclosing_num)
func1 ()
print(global_num)
上述代码的运行结果如下所示:

global_num = 1
def func1():
… enclosing_num = 2
… global global_num #使用global关键字声明
… print(global_num)
… global_num = 123
… print(global_num)
… def func2():
… nonlocal enclosing_num
… print(enclosing_num) #使用nonlocal关键字声明
… enclosing_num = 456
… func2 ()
… print(enclosing_num)

func1 ()
1
123
2
456

print(global_num)
123

只有模块(module),类(class)和函数(def、lambda)才会引入新的作用域,if/elif/else/、try/except、for/while 等语句则不会引入新的作用域,即外部可以访问在这些语句内定义的变量。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值