Python札记21_嵌套函数

在上一篇 Python札记20_递归、传递 文章中重点介绍了递归函数中的斐波那契数列的实现,以及函数当做参数进行传递的知识。函数不仅可以当做对象进行传递,还能在函数里面嵌套另一个函数,称之为函数嵌套

通过一个例子来理解嵌套函数的使用:

def foo():   # foo()函数中内嵌了bar函数
    def bar():
        print("bar() is running")
    print("foo() is running")

foo()  # 运行结果显示bar没有被调用和执行

结果

foo() is running     #bar函数没有运行,因为它没有被调用

如果想让bar()执行,进行如下操作:

def foo():   # foo()函数中内嵌了bar函数
    def bar():
        print("bar() is running")
    bar()  # 调用bar函数:只有当bar被调用,才会执行bar函数的代码块
    print("foo() is running")
foo()

结果:

bar() is running
foo() is running
image.png

函数bar是在foo里面进行定义的,它的作用域只在foo函数范围之内;如果把bar函数放在外面执行,调用则会报错:

同时bar的变量也会受到far函数的约束:

def foo():
   a = 1
   def bar():
       a = a + 1
       print("bar()a=", a)
   bar()
   print("foo()a=", a)
foo()`

运行报错:

  • bar里面使用了变量aPython解释器会认为a变量是建立在bar内部的局部变量nonlocal,而不是引用的外部对象。
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-23-0c4c07078810> in <module>
      6     bar()
      7     print("foo()a=", a)
----> 8 foo()

<ipython-input-23-0c4c07078810> in foo()
      4         a = a + 1
      5         print("bar()a=", a)
----> 6     bar()
      7     print("foo()a=", a)
      8 foo()

<ipython-input-23-0c4c07078810> in bar()
      2     a = 1
      3     def bar():
----> 4         a = a + 1
      5         print("bar()a=", a)
      6     bar()

UnboundLocalError: local variable 'a' referenced before assignment

使用nonlocal关键字来解决:

def foo():
    a = 1
    def bar():
        nonlocal a    # 指定a不是bar内部的局部变量。
        a = a + 1
        print("bar()a=", a)
    bar()
    print("foo()a=", a)
foo()
image.png

注意a值的变化

  • 定义变量a=1
  • 执行bar函数,a变成2
  • 最后执行第二个print函数,a=2,程序是按照自顶向下的顺序执行整个代码块。
def foo():
    a = 1
    def bar():
        a = 1   # a是bar函数的局部变量
        a = a + 1
        print("bar()a=", a)
    bar()
    print("foo()a=", a)
foo()
image.png
def foo():
    a = 1
    def bar(a):    # 给bar传递参数
        a = a + 1
        print("bar()a=", a)
    bar(a)
    print("foo()a=", a)
foo()
image.png

嵌套函数的实际使用:计算重力的函数

def weight(g):
    def cal_mg(m):
        return m * g
    return cal_mg   # weight函数的返回值是cal_mg函数执行的结果

w = weight(9.8)   # 参数g = 9.8
mg = w(5)  # 参数m = 5
mg

理解:

  • w = weight(10):weight函数中传递了参数10
  • w 引用的是一个函数对象(cal_mg);cal_mg是一个动态函数
  • w(10)向所引用的函数对象cal_mg传递了参数5
  • 计算并返回mg的值
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。