• 名称空间与作用域


    # 名称空间指的是存放名字与值绑定关系的地方

    # 内置名称空间(python解释器启动就有):python解释器内置的名字:max,len,print
    # 全局名称空间(执行python文件时生效):没有缩进的,顶着文件头写的 # 文件级别的名字
    # 局部名称空间(调用函数时生效,调用结束失效):函数内部定义的名字

    # 加载顺序:内置>>全局>>局部
    # 访问名字的顺序:局部>>全局>>内置

    # max=2
    # def foo():
    # max=1
    # print(max)
    #
    # foo() # 1

    # max=2
    # def foo():
    # # max=1
    # print(max)
    #
    # foo() # 2

    # # max=2
    # def foo():
    # # max=1
    # print(max)
    #
    # foo() # <built-in function max>
    # 一定不要让你的变量名和python内置的名字重复,否则会有覆盖的效果

    # 作用域
    # 全局作用域(全局范围):内置名称空间与全局名称空间的名字,全局存活,全局有效
    # 局部作用域(局部范围):局部名称空间的名字,临时存活,局部有效
    # globals()查看全局作用域的名字
    # # locals()查看局部作用域的名字
    # print(globals())
    # print(locals())

    # max=2
    # def func():
    # max=1
    # print(max)
    #
    # func()

    # x='gobal'
    # def f1():
    # x=1
    # def f2():
    # x=2
    # def f3():
    # x=3
    # print(x)
    # f3()
    # f2()
    #
    # f1()

    # x=100
    # def func():
    # global x
    # x=1
    #
    # func()
    # print(x)

    # x='global'
    # def f1():
    # x=1
    # def f2():
    # global x
    # x=0
    # f2()
    #
    # f1()
    # print(x) # 0

    # x='global'
    # def f1():
    # x=1
    # def f2():
    # nonlocal x
    # x=0
    # f2()
    #
    # f1()
    # print(x) # global

    # 打破函数层级限制来调用函数
    # def outter():
    # def inner():
    # print('inner')
    # return inner
    #
    # f=outter()
    # print(f) # <function outter.<locals>.inner at 0x0000025818424D38>

    # def bar():
    # f()
    #
    # bar() # inner

    # 函数的作用域关系是在函数定义阶段就已经固定了,与函数的调用位置无关
    # x=1
    # def outter():
    # x=2
    # def inner():
    # print('inner',x)
    # return inner
    #
    # f=outter()
    #
    # def bar():
    # x=3
    # f()
    #
    # bar() # inner 2
  • 相关阅读:
    有关Python Selenium的使用心得
    win11 资源管理器右键菜单改回老样式
    js关闭被打开的iframe页面,并在新窗口打开
    sqlplus文件查看oracle自带命令的执行过程
    xtrabackup+MySQL8全备+增备脚本
    DG:有多个备库如何切换
    MySQL匿名空用户名处理
    xtrabackup: error: xb_load_tablespaces() failed with error code 57
    四月常用工具汇总
    yum安装openldap,slapd.conf文件
  • 原文地址:https://www.cnblogs.com/0B0S/p/11971558.html
Copyright © 2020-2023  润新知