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
>>>

 
發佈了41 篇原創文章 · 獲贊 1 · 訪問量 3371
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章