zoukankan      html  css  js  c++  java
  • python中的内嵌函数

    1、

    >>> def a():
        print("fun a is running!")
        def b():
            print("fun b is running!")
        b()
    
        
    >>> a()         ## 示例中函数b是函数a的内嵌函数
    fun a is running!
    fun b is running!
    >>> b()      ## 内嵌函数只能在函数内部调用
    Traceback (most recent call last):
      File "<pyshell#719>", line 1, in <module>
        b()
    NameError: name 'b' is not defined

    2、

    >>> def a():
        x = 100
        def b():
            print("x = ",x)
        b()
    
        
    >>> a()      ## 内嵌函数可以调用外层函数的变量
    x =  100

    3、

    >>> x = 500
    >>> def a():
        x = 100
        def b():
            x = 10
            print("x = ", x)
        b()
    
        
    >>> a()        ## 此种清空,函数调用自身定义的变量
    x =  10

    4、

    >>> x = 500
    >>> id(x)
    2137596545936
    >>> def a():
        x = 100
        print(id(x))
        def b():
            x = 10
            print(id(x))
        b()
    
        
    >>> a()
    140731529356032
    140731529353152
    ## LEGB原则 ????
  • 相关阅读:
    Leetcode字符串算法
    Leetcode基础算法结构-目录结构
    python日志-loguru日志管理
    FastApi
    python-hashlib
    excel数据操作
    yagmail自动发邮件
    python-sys
    集合
    文件操作
  • 原文地址:https://www.cnblogs.com/liujiaxin2018/p/14481334.html
Copyright © 2011-2022 走看看