Python 关键字 global、nonlocal、yield用法
生活随笔
收集整理的這篇文章主要介紹了
Python 关键字 global、nonlocal、yield用法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. global
global 關鍵字用于表示某個變量是屬于全局的,而不是局部變量。先看個例子:
In [82]: x = 10In [83]: def func():...: x += 1...: print(x)...: In [84]: func()
---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
<ipython-input-84-bd1982955a12> in <module>
----> 1 func()<ipython-input-83-44beed2eef27> in func()1 def func():
----> 2 x += 13 print(x)4 UnboundLocalError: local variable 'x' referenced before assignment
報錯的原因是解釋器在運行代碼時認為 x 為局部變量,但是很顯然在 func 函數內找不到對該變量的定義,所以會報錯。使用 global 來聲明該變量為全局變量:
In [85]: def func():...: global x...: x += 1...: print(x)...: In [86]: func()
11In [87]:
2. nonlocal
關鍵詞 nonlocal 常用于函數嵌套中,聲明變量為非局部變量。
In [89]: def g():...: i = 0...: def f():...: if i>1:...: i = 0...: i += 1...: i += 1...: f()...: print(i)...: In [90]: g()
---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
<ipython-input-90-5fd69ddb5074> in <module>
----> 1 g()<ipython-input-89-4570c8ebdac0> in g()6 i += 17 i += 1
----> 8 f()9 print(i)10 <ipython-input-89-4570c8ebdac0> in f()2 i = 03 def f():
----> 4 if i>1:5 i = 06 i += 1UnboundLocalError: local variable 'i' referenced before assignment
使用 nonlocal 聲明變量屬于非局部變量,
In [91]: def g():...: i = 0...: def f():...: nonlocal i...: if i>1:...: i = 0...: i += 1...: i += 1...: f()...: print(i)...: In [92]: g()
2In [93]:
3. yield
yield 是一種特殊的 return 。是因為執行遇到 yield 時,立即返回,這是與 return 的相似之處。不同之處在于:下次進入函數時直接到 yield 的下一個語句,而 return 后再進入函數,還是從函數體的第一行代碼開始執行。
帶 yield 的函數是生成器,通常與 next 函數結合用。下次進入函數,意思是使用 next 函數進入到函數體內。
看個下面這個例子,調用 fun() 函數后會立即執行函數
In [2]: def fun():...: print("enter func")...: return "hello"...: In [3]: ret = fun()
enter funcIn [4]: ret
Out[4]: 'hello'
下面新定義的函數帶有 yield 關鍵字,所以函數 fun() 是生成器函數。調用 fun() 返回一個迭代器對象,使用 next() 方法調用之后會返回到 yield 語句之處,再次調用 next() 之后會接著上次執行到的地方再次執行。
In [5]: def fun():...: print("enter func")...: yield 100...: print("yield next sentence")...: In [6]: ret = fun()In [7]: next(ret)
enter func
Out[7]: 100In [8]: next(ret)
yield next sentence
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-8-2216548e65ed> in <module>
----> 1 next(ret)StopIteration:
總結
以上是生活随笔為你收集整理的Python 关键字 global、nonlocal、yield用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 买社保多少钱啊?
- 下一篇: Python 列表生成式的使用