問題描述
從函數返回多個值的最佳方法是什麼? (What's the best way to return multiple values from a function?)
我有一個函數,我需要對字符串做一些事情。我需要該函數返回一個指示操作是否成功的布爾值,並且我還需要返回修改後的字符串。
在 C# 中,我會為字符串使用 out 參數,但在 Python 中沒有等效參數。我對 Python 還是很陌生,我唯一能想到的就是返回一個帶有布爾值和修改後的字符串的元組。
相關問題:函數返回多個值是pythonic嗎?
參考解法
方法 1:
def f(in_str):
out_str = in_str.upper()
return True, out_str # Creates tuple automatically
succeeded, b = f("a") # Automatic tuple unpacking
</code></pre>
方法 2:
Why not throw an exception if the operation wasn't successful? Personally, I tend to be of the opinion that if you need to return more than one value from a function, you should reconsider if you're doing things the right way or use an object.
But more directly to the point, if you throw an exception, you're forcing them to deal with the problem. If you try to return a value that indicates failure, it's very well possible somebody could not check the value and end up with some potentially hard to debug errors.
方法 3:
Return a tuple.
def f(x):
# do stuff
return (True, modified_string)
success, modified_string = f(something)
方法 4:
Returning a tuple is the usual way to do this in Python.
方法 5:
Throwing an exception for failure is one good way to proceed, and if you're returning a lot of different values, you can return a tuple. For the specific case you're citing, I often take an intermediate approach: return the modified string on success, and return None on failure. I'm enough of an unreconstructed C programmer to want to return a NULL pointer to char on failure.
If I were writing a routine to be used as part of a larger library and consumed by other developers, I'd throw an exception on failure. When I'm eating my own dogfood, I'll probably return different types and test on return.
(by John Rutherford、John Millikin、Jason Baker、rmmh、Chris Upchurch、tuxedo)
參考文件