zoukankan      html  css  js  c++  java
  • python全局变量与局部变量

    python默认作用域中声明的变量都是局部变量,当一个变量在局部作用域中没有声明,则会去找全局作用域中的这个变量。

    例子1:

    a = 100
    
    def test_local():
        print(id(a)) # 140732287020976
        # 由于局部作用域尚未声明a,取的是全局变量a的id
        a = 123
        print(id(a)) # 140732287021712
        # 此时a表示局部变量a
    
    
    if __name__ == "__main__":
        test_local()
        print(id(a)) # 140732287020976
        # test_local中对局部变量a的声明并不会影响到全局变量
    

    例子2:

    a = 100
    
    def test_local():
        a = a+1
        # 这里的a不会取到全局变量a
        print(a)
    
    
    if __name__ == "__main__":
        test_local()
        print(a)
        
    # Traceback (most recent call last):
    #   File "python_test.py", line 9, in <module>
    #     test_local()
    #   File "python_test.py", line 4, in test_local
    #     a = a+1
    # UnboundLocalError: local variable 'a' referenced before assignment
    

    使用关键字global能够修改全局变量的内存地址

    例1:

    a = 100
    
    def test_local():
        global a
        print(id(a)) # 140732285054896
        # 此时a表示全局变量
        a = 123
        print(id(a)) # 140732285055632
    
    
    if __name__ == "__main__":
        test_local()
        print(id(a)) # 140732285055632
        # 全局变量a被修改
    
    

    例2:

    a = [1,2,3]
    
    def test_local():
        print(id(a)) # 2454725550728
        a.append(4)
        print(id(a)) # 2454725550728
        # 修改可变对象的值不会改变对象的内存地址
    
    
    if __name__ == "__main__":
        test_local()
        print(a) # [1, 2, 3, 4]
        # 全局可变对象a的值被修改了
        print(id(a)) # 2454725550728
        # 但是内存地址没有被修改
    
  • 相关阅读:
    手机自动化
    记录
    Linux 死机了怎么办
    前端源码
    LNMP环境
    PHP学习之路(一)
    py
    蜘蛛问题
    mongodb
    【HTML/XML 2】XML基础知识点总结
  • 原文地址:https://www.cnblogs.com/luozx207/p/12198111.html
Copyright © 2011-2022 走看看