gpt4 book ai didi

python - 如何指定参数是 Python 文档字符串中特定对象的列表

转载 作者:IT老高 更新时间:2023-10-28 21:33:32 25 4
gpt4 key购买 nike

我真的很喜欢在 Python 中使用文档字符串来在项目超出一定大小时指定类型参数。

我无法找到用于指定参数是特定对象列表的标准,例如在 Haskell 类型中,我会使用 [String] 或 [A]。

当前标准(PyCharm 编辑器可识别):

def stringify(listOfObjects):
"""
:type listOfObjects: list
"""
return ", ".join(map(str, listOfObjects))

我更喜欢什么:

选项 1

def stringify(listOfObjects):
"""
:type listOfObjects: list<Object>
"""
return ", ".join(map(str, listOfObjects))

选项 2

def stringify(listOfObjects):
"""
:type listOfObjects: [Object]
"""
return ", ".join(map(str, listOfObjects))

我想这不是一个很好的例子 - 更相关的用例是列表中的对象必须是特定类型的用例。

更好的例子

class Food(Object):
def __init__(self, calories):
self.calories = calories

class Apple(Food):
def __init__(self):
super(self, 200)

class Person(Object):
energy = 0
def eat(foods):
"""
:type foods: [Food] # is NOT recognised by editor
"""
for food in foods:
energy += food.calories

所以,除了我饿了之外,这个例子说明如果用错误类型的对象列表调用,代码会中断。因此,记录的重要性不仅在于它需要一份 list ,而且还需要一份食物 list 。

相关问题 How can I tell PyCharm what type a parameter is expected to be?请注意,我正在寻找比上述更具体的答案。

最佳答案

PyCharm's manual 的评论部分开发人员有一个很好的提示:

#: :type: dict of (str, C)
#: :type: list of str

它对我很有效。现在它让我想知道在 Python 中记录参数化类的最佳方法是什么:)。

关于python - 如何指定参数是 Python 文档字符串中特定对象的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17824280/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com