那如果你想從一個函數(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ù)情況都不是)。