08内嵌函数

视频21
1.内部函数作用域 都在外部函数之内
例一
>>> def fun1():
 print('fun1正在被调用···')
 def fun2():
  print('fun2正在被调用···')
 fun2()
 
>>> fun1()
fun1正在被调用···
fun2正在被调用···
>>> fun2()
Traceback (most recent call last):
  File "<pyshell#40>", line 1, in <module>
    fun2()
NameError: name 'fun2' is not defined


2.闭包closure(定义:如果在一个内部函数里,对外部作用域(非全局作用域)的变量进行引用,那么内部函数被称为闭包)
闭包需要满足以下三个条件:
①存在于嵌套关系的函数中
②嵌套的内部函数引用了外部函数的变量
③嵌套的外部函数会将内部函数名作为返回值返回
>>> def outer(start=0):
 count = [start]
 def inner():
  count[0] += 1
  return count[0]
 return inner
>>> out = outer(5)
>>> print(out())
6


例二
>>> def funx(x):
 def funy(y):
  return x*y
 return funy
>>> i = funx(8)
>>> i
<function funx.<locals>.funy at 0x00000232BDFFC840>
>>> type(i)
<class 'function'>
>>> i(5)
40
>>> funx(8)(5)
40
例三
>>> def fun1():
 x = 5
 def fun2():
  x *=x
  return x
 return fun2()
>>> fun1()
Traceback (most recent call last):
  File "<pyshell#60>", line 1, in <module>
    fun1()
  File "<pyshell#59>", line 6, in fun1
    return fun2()
  File "<pyshell#59>", line 4, in fun2
    x *=x
UnboundLocalError: local variable 'x' referenced before assignment


在赋值前引用的局部变量x
 #运行至return fun2(),内部函数试图修改全局变量(相对而言),Python用shadowing隐藏全局变量(相对而言),即在内部函数fun2()的外部空间中的x = 5被屏蔽,故x未被赋值
 容器类型对代码改造(1.列表不是存放在栈里面,是一个单独的容器,所以在内部函数里可以进行修改2.列表储存在堆内存中,相当于都是全局变量)

例三
>>> def fun1():
 x = [5]
 def fun2():
  x[0] *=x[0]
  return x[0]
 return fun2()
>>> fun1()
25
 #关键字nonlocal改造
>>> def fun1():
 x = 5
 def fun2():
  nonlocal x
  x *=x
  return x
 return fun2()
>>> fun1()
25
>>>

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值