• 名称空间与作用域(2)


    一:名称空间:就是用来存放名字的内存空间
    名称空间分为三大类:
    1、内置名称空间:存放python解释器提供的名字
    生命周期:python解释器启动则产生,python解释器关闭则销毁
    2、全局名称空间:顶级的名字
    生命周期:开始python程序则启动,python程序运行完毕则销毁
    #示例
    x = 1
    y = 2
    if True:
        z = 3
    
    while True:
        bbb = 44
    

     3.局部名称空间:在函数内部定义的名字

         生命周期:调用函数则产生,函数调用结束则会立即销毁

    def f1(aaa):
        # aaa=555
        def f2():
            ccc = 666
    
    f1(555)

    二、名字访问的优先级:基于当前所在的位置向上查找(局部-》全局-》内置)

    #例1
    # len=111
    
    def f1():
        # len=222
        def f2():
            # len=333
            print(len)
        f2()
    
    f1()
    
    
    #例2
    def f1():
        print(len)
    
    # f1()
    len=111
    # f1()
    
    def foo():
        len=333333
        f1()
    
    
    def bar():
        len=44444
        f1()
    
    foo()
    bar()
    
    
    
    #例3:
    aaa=333
    
    def f1():
        # print(aaa)
        # print(len)
        x=111
        def ff1():
            print("fff1===>x: ",x)
        ff1()
    
    def f2():
        # print(aaa)
        # print(len)
        y=222
    
    f1()
    f2()
    
    
    #例4:
    len=111
    
    def f1():
        print(len)
    
    
    
    def f2():
        len=33333333333333333333
        f1()
    
    f2()
    

    注:名称空间的嵌套关系是在函数定义阶段扫描语法的时候生成的

    x=111
    
    def func():
        print(x)
        y=2222
    
    func()
    

    三、作用域

    全局作用域:内置+全局名称空间中的名字
    特点:全局存活、全局有效

    局部作用域:局部名称空间空间的名字
    特点:临时存活,局部有效

    四、global、nonlocal

    4.1 global:在函数内声明名字是来自于全局的
    l=[1,2,3]
    def func():
        l[0]=111
    func()
    print(l)
    
    x=10
    def func():
        global x
        x=20
    func()
    print(x)
    View Code
    4.2 nonlocal在函数内声明名字是来自于外层函数的
    x=333
    def f1():
        # x=111
        def f2():
             # global x
             nonlocal x
             x=222
        f2()
        print(x)
    
    f1()
    View Code

     



     
  • 相关阅读:
    Leetcode-645 Set Mismatch
    2017百度软研(C++)
    二叉树中任意两个节点的最近公共祖先
    不用加减乘除做加法
    一些leetcode算法题
    Leetcode 98. Validate Binary Search Tree
    C++ 通过ostringstream 实现任意类型转string
    Leetcode 215. Kth Largest Element in an Array
    382. Linked List Random Node
    一些基础函数的实现
  • 原文地址:https://www.cnblogs.com/datatool/p/13458158.html
Copyright © 2020-2023  润新知