前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python - 变量的作用域

Python - 变量的作用域

作者头像
小菠萝测试笔记
发布2020-06-09 15:25:59
1.6K0
发布2020-06-09 15:25:59
举报

变量作用域

  • Python能够改变变量作用域的代码段是 、 class 、 lamda.

def

  • 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内建函数作用域 > 全局变量作用域 > 局部变量作用域就好了

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-03-19 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 变量作用域
  • 局部变量vs全局变量
  • global的作用
    • 执行结果
      • 切记
      • if/elif/else、try/except/finally、for/while
        • 执行结果
        • 变量搜索路径是:局部变量->全局变量
          • 执行结果
          • Python的LEGB规则
            • 什么是内建函数呢?
              • 执行结果
              • 看LEGB的栗子
                • 执行结果
                  • 当我们改动下代码,把局部变量注释
                    • 执行结果
                      • 现在把外部函数变量也注释掉
                        • 执行结果
                          • 现在把全局变量也注释掉
                            • 执行结果
                              • 注意点
                              领券
                              问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档