zoukankan      html  css  js  c++  java
  • Python

    变量作用域

    • Python能够改变变量作用域的代码段是 def 、 class 、 lamda. 
    • 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内建函数作用域 > 全局变量作用域 > 局部变量作用域就好了

  • 相关阅读:
    在Eclipse中使用JUnit4进行单元测试(上)
    SVN和Subclipse安装和使用指南汇总
    在windows下搭建SVN服务器
    学会SVN的应用源代码托管
    SVN中检出(check out) 和 导出(export) 的区别
    .NET平台三层应用程序框架搭建(一)
    Winform dataGridview 为每一个单元格制定一个tooptip
    SQL row_number() over() 来自动产生行号
    Winform datagridview 设置单元格为只读属性
    SQL 把字符创分割成两个字符串
  • 原文地址:https://www.cnblogs.com/poloyy/p/12525020.html
Copyright © 2011-2022 走看看