Python - 变量的作用域

简介: Python - 变量的作用域

变量作用域


  • Python 能够改变变量作用域的代码段是 defclasslamda.
  • if/elif/else、try/except/finally、for/while 并不能涉及变量作用域的更改,也就是在这些代码块中的变量,外部也是可以访问的
  • 变量搜索路径是:局部变量->全局变量

 

局部变量 vs 全局变量


  • 局部变量:在函数内部,类内部,lamda.的变量,它的作用域仅在函数、类、lamda 里面
  • 全局变量:在当前 py 文件都生效的变量

 

global的作用


让局部变量变成全局变量

def tests():
    global vars
    vars = 6
tests()
print(vars)

执行结果

6

切记

先 global 声明一个变量,再给这个变量赋值,不能直接 global vars = 6 ,会报错哦!!

 

if/elif/else、try/except/finally、for/while


# while
while True:
    var = 100
    break
print(var)
# try except
try:
    var = 111
    raise Exception
except:
    print(var)
print(var)
# if
if True:
    var = 222
print(var)
# elif
if False:
    pass
elif True:
    var = 333
print(var)
# else
if False:
    pass
else:
    var = 444
print(var)
# for
for i in range(0, 1):
    var = 555
print(var)


执行结果

100
111
111
222
333
444
555


变量搜索路径是:局部变量->全局变量


def test():
    var = 6
    print(var)  #
var = 5
print(var)
test()
print(var)


执行结果

5

6

5

 

Python 的 LEGB 规则


  • L-Local(function);函数内的变量
  • E-Enclosing function locals;外部嵌套函数的变量
  • G-Global(module);函数定义所在模块的变量
  • B-Builtin(Python);Python内建函数的名字空间

这是我们代码找变量的顺序,倘若最后一个python内建函数也没有找到的话就会报错了

 

什么是内建函数呢?

无需安装第三方库,可以直接调用的函数,让我们来看看有哪些内建函数:

print(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']

 

看LEGB的栗子


# Python内建函数的变量
x = int(0.22)
# 全局变量
x = 1
def foo():
    # 外部函数变量
    x = 2
    def innerfoo():
        # 局部变量
        x = 3
        print('local ', x)
    innerfoo()
    print('enclosing function locals ', x)
foo()
print('global ', x)


执行结果

local  3

enclosing function locals  2

global  1

 

当我们改动下代码,把局部变量注释

# Python内建函数的变量
x = int(0.22)
# 全局变量
x = 1
def foo():
    # 外部函数变量
    x = 2
    def innerfoo():
        # 局部变量
        # x = 3   ##### 被注释掉了
        print('local ', x)
    innerfoo()
    print('enclosing function locals ', x)
foo()
print('global ', x)


执行结果

local  2

enclosing function locals  2

global  1

 

现在把外部函数变量也注释掉

# Python内建函数的变量
x = int(0.22)
# 全局变量
x = 1
def foo():
    # 外部函数变量
    # x = 2 ###注释
    def innerfoo():
        # 局部变量
        # x = 3 ###注释
        print('local ', x)
    innerfoo()
    print('enclosing function locals ', x)
foo()
print('global ', x)


执行结果

local  1

enclosing function locals  1

global  1

 

现在把全局变量也注释掉

# Python内建函数的变量
x = int(0.22)
# 全局变量
# x = 1
def foo():
    # 外部函数变量
    # x = 2
    def innerfoo():
        # 局部变量
        #x = 3
        print('local ', x)
    innerfoo()
    print('enclosing function locals ', x)
foo()
print('global ', x)


执行结果

local  0

enclosing function locals  0

global  0

 

注意点

其实一般不会用到外部嵌套函数的作用域,所以只要记得Python内建函数作用域 > 全局变量作用域 > 局部变量作用域就好了

相关文章
|
18天前
|
Shell Python
python 和shell 变量互相传递
python 和shell 变量互相传递
24 0
|
1月前
|
存储 Java Python
python变量、常量、数据类型
python变量、常量、数据类型
|
1天前
|
Python
在Python中,全局变量和局部变量是两种不同类型的变量
Python中的全局变量在函数外部定义,作用域覆盖整个程序,生命周期从开始到结束。局部变量仅限于函数内部,生命周期从调用到返回。在函数内修改全局变量需用`global`关键字声明,否则会创建局部变量。
12 3
|
3天前
|
Python
python 变量的定义和使用详解
python 变量的定义和使用详解
8 0
|
3天前
|
Java C# 开发者
Python 中的类型注解是一种用于描述变量、函数参数和返回值预期类型的机制
Python的类型注解提升代码可读性和可维护性,虽非强制,但利于静态类型检查(如Mypy)。包括:变量注解、函数参数和返回值注解,使用内置或`typing`模块的复杂类型,自定义类型注解,以及泛型模拟。类型注解可在变量声明、函数定义和注释中使用,帮助避免类型错误,提高开发效率。
16 6
|
5天前
|
Python
python变量未定义(NameError)
【5月更文挑战第1天】
15 1
|
13天前
|
Python
python函数的返回值、嵌套方式以及函数中的变量(二)
python函数的返回值、嵌套方式以及函数中的变量(二)
|
13天前
|
存储 Python 容器
python函数的返回值、嵌套方式以及函数中的变量(一)
python函数的返回值、嵌套方式以及函数中的变量(一)
|
13天前
|
运维 监控 Serverless
Serverless 应用引擎产品使用之阿里函数计算中在自定义环境下用debian10运行django,用官方层的python3.9,配置好环境变量后发现自定义层的django找不到了如何解决
阿里云Serverless 应用引擎(SAE)提供了完整的微服务应用生命周期管理能力,包括应用部署、服务治理、开发运维、资源管理等功能,并通过扩展功能支持多环境管理、API Gateway、事件驱动等高级应用场景,帮助企业快速构建、部署、运维和扩展微服务架构,实现Serverless化的应用部署与运维模式。以下是对SAE产品使用合集的概述,包括应用管理、服务治理、开发运维、资源管理等方面。
22 3
|
16天前
|
Python
Day4作用域,Python关键字global和nonlocal使用
作用域,Python关键字global和nonlocal使用
4 0