如何在 Python 中从函数返回对象?
pythonserver side programmingprogramming更新于 2025/3/25 2:52:17
Python 函数退出并将值返回给其调用者。函数的目标通常是接收输入并返回某些内容。一旦执行 return 语句,即使它不是函数中的最后一个语句,也会立即停止函数的执行。
返回值的函数有时称为有结果函数。
示例
def sum(a,b): return a+b sum(5,16)
输出
21
Python 中的所有内容,几乎所有内容都是对象。列表、字典、元组也是 Python 对象。下面的代码显示了一个返回 Python 对象的 Python 函数;一个字典。
示例
# This function returns a dictionary def foo(): d = dict(); d['str'] = "Tutorialspoint" d['x'] = 50 return d print foo()
输出
{'x': 50, 'str': 'Tutorialspoint'}
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

