Python札记21_嵌套函数

浏览: 1151

在上一篇 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的值



推荐 0
本文由 皮大大 创作,采用 知识共享署名-相同方式共享 3.0 中国大陆许可协议 进行许可。
转载、引用前需联系作者,并署名作者且注明文章出处。
本站文章版权归原作者及原出处所有 。内容为作者个人观点, 并不代表本站赞同其观点和对其真实性负责。本站是一个个人学习交流的平台,并不用于任何商业目的,如果有任何问题,请及时联系我们,我们将根据著作权人的要求,立即更正或者删除有关内容。本站拥有对此声明的最终解释权。

0 个评论

要回复文章请先登录注册