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

多個return值

那如果你想從一個函數(shù)里返回兩個變量而不是一個呢?
新手們有若干種方法。最著名的方法,是使用global關鍵字。讓我們看下這個沒用的例子:

def profile():
    global name
    global age
    name = "Danny"
    age = 30

profile()
print(name)
# Output: Danny

print(age)
# Output: 30

注意: 不要試著使用上述方法。重要的事情說三遍,不要試著使用上述方法!

有些人試著在函數(shù)結束時,返回一個包含多個值的tuple(元組),list(列表)或者dict(字典),來解決這個問題。這是一種可行的方式,而且使用起來像一個黑魔法:

def profile():
    name = "Danny"
    age = 30
    return (name, age)

profile_data = profile()
print(profile_data[0])
# Output: Danny

print(profile_data[1])
# Output: 30

或者按照更常見的慣例:

def profile():
    name = "Danny"
    age = 30
    return name, age

這是一種比列表和字典更好的方式。不要使用global關鍵字,除非你知道你正在做什么。global也許在某些場景下是一個更好的選擇(但其中大多數(shù)情況都不是)。

上一篇:Python/C API下一篇:<code>Filter</code>