【发布时间】:2023-03-19 14:48:02
【问题描述】:
假设我有一个返回多个值的函数
import numpy as np
def add_and_raisepower(x, y):
"""
1) Add inputs **x** and **y** and return the result.
2) Raise **x** to the power of **y**, multiply this
result by an array of one's and return the result.
:type x: float
:param x: The first input number
:type y: float
:param y: The second input number
:rtype val1: float
:rtype val2: numpy.array(float)
"""
val1 = x + y
val2 = np.ones(100)*(x**y)
return val1, val2
我关心的是文档字符串中的:rtype: 注释;如果一个函数返回多个值,就像这个例子一样,:rtype: 应该如何写在文档字符串中(根据 PEP-8)?
通常对于只返回一个值的函数,:rtype: 会写成类似
"""
...
:rtype: int
"""
这里没有指定返回的变量名,因为没有关系,因为只有一个返回值。
我知道理想情况下我应该尝试将我的函数分解为更简单的函数,这对于上面的add_and_raisepower 来说当然是可能的,但是我只是用这个作为一个玩具示例来说明这个问题。
【问题讨论】:
-
当你“返回多个值”时,你只是返回一个元组。它可以是元组所指示的任何内容。
-
如果对参数和返回值使用类型注释,答案会有什么不同?