鍍金池/ 教程/ Python/ Global和Return
<code>open</code>函數(shù)
Python 2系列版本
可迭代對(duì)象(Iterable)
異常
在函數(shù)中嵌入裝飾器
你的第一個(gè)裝飾器
上下文管理器(Context managers)
<code>set</code>(集合)數(shù)據(jù)結(jié)構(gòu)
裝飾器類
字典推導(dǎo)式(<code>dict</code> comprehensions)
<code>Reduce</code>
捐贈(zèng)名單
<code>Filter</code>
<code>try/else</code>從句
*args 的用法
<code>dir</code>
處理異常
<code>else</code>從句
對(duì)象自省
For - Else
18. 一行式
Python 3.2及以后版本
Global和Return
基于類的實(shí)現(xiàn)
容器(<code>Collections</code>)
23. 協(xié)程
推薦閱讀
譯者后記
<code>*args</code> 和 <code>**kwargs</code>
**kwargs 的用法
生成器(Generators)
迭代(Iteration)
基于生成器的實(shí)現(xiàn)
將函數(shù)作為參數(shù)傳給另一個(gè)函數(shù)
日志(Logging)
三元運(yùn)算符
<code>inspect</code>模塊
枚舉
Map,F(xiàn)ilter 和 Reduce
各種推導(dǎo)式(comprehensions)
從函數(shù)中返回函數(shù)
列表推導(dǎo)式(<code>list</code> comprehensions)
處理多個(gè)異常
帶參數(shù)的裝飾器
對(duì)象變動(dòng)(Mutation)
22. 目標(biāo)Python2+3
迭代器(Iterator)
虛擬環(huán)境(virtualenv)
<code>__slots__</code>魔法
什么時(shí)候使用它們?
Python/C API
<code>Map</code>
SWIG
授權(quán)(Authorization)
裝飾器
一切皆對(duì)象
使用C擴(kuò)展
使用 <code>*args</code> 和 <code>**kwargs</code> 來(lái)調(diào)用函數(shù)
17. <code>lambda</code>表達(dá)式
集合推導(dǎo)式(<code>set</code> comprehensions)
<code>type</code>和<code>id</code>
在函數(shù)中定義函數(shù)
<code>finally</code>從句
CTypes
調(diào)試(Debugging)
使用場(chǎng)景
生成器(Generators)
多個(gè)return值
關(guān)于原作者
函數(shù)緩存 (Function caching)
Python進(jìn)階

Global和Return

你也許遇到過(guò), python中一些函數(shù)在最尾部有一個(gè)return關(guān)鍵字。你知道它是干嘛嗎?它和其他語(yǔ)言的return類似。我們來(lái)檢查下這個(gè)小函數(shù):

def add(value1, value2):
    return value1 + value2

result = add(3, 5)
print(result)
# Output: 8

上面這個(gè)函數(shù)將兩個(gè)值作為輸入,然后輸出它們相加之和。我們也可以這樣做:

def add(value1,value2):
    global result
    result = value1 + value2

add(3,5)
print(result)
# Output: 8

那首先我們來(lái)談?wù)劦谝欢我簿褪前?code>return關(guān)鍵字的代碼。那個(gè)函數(shù)把值賦給了調(diào)用它的變量(也就是例子中的result變量)。
大多數(shù)境況下,你并不需要使用global關(guān)鍵字。然而我們也來(lái)檢查下另外一段也就是包含global關(guān)鍵字的代碼。 那個(gè)函數(shù)生成了一個(gè)global(全局)變量result。

global在這的意思是什么?global變量意味著我們可以在函數(shù)以外的區(qū)域都能訪問(wèn)這個(gè)變量。讓我們通過(guò)一個(gè)例子來(lái)證明它:

# 首先,是沒(méi)有使用global變量
def add(value1, value2):
    result = value1 + value2

add(2, 4)
print(result)

# Oh 糟了,我們遇到異常了。為什么會(huì)這樣?
# python解釋器報(bào)錯(cuò)說(shuō)沒(méi)有一個(gè)叫result的變量。
# 這是因?yàn)閞esult變量只能在創(chuàng)建它的函數(shù)內(nèi)部才允許訪問(wèn),除非它是全局的(global)。
Traceback (most recent call last):
  File "", line 1, in
    result
NameError: name 'result' is not defined

# 現(xiàn)在我們運(yùn)行相同的代碼,不過(guò)是在將result變量設(shè)為global之后
def add(value1, value2):
    global result
    result = value1 + value2

add(2, 4)
print(result)
6

如我們所愿,在第二次運(yùn)行時(shí)沒(méi)有異常了。在實(shí)際的編程時(shí),你應(yīng)該試著避開global關(guān)鍵字,它只會(huì)讓生活變得艱難,因?yàn)樗肓硕嘤嗟淖兞康饺肿饔糜蛄恕?/p>