如何指定参数是Python docstring中特定对象的列表

2024-05-19 20:53:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我真的很喜欢在Python中使用docstring来指定当项目超过一定大小时的类型参数。

我很难找到一个标准来指定参数是特定对象的列表,例如在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

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

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


Tags: 对象self类型map列表returnobjectdef
3条回答

以google风格编写docstring时,可以执行以下操作:

class ToDocument(object):
    """This is my Documentation.

    Args:
        typed_list (:obj:`list` of :obj:`str`): Description of typed list

    """
    ...

在狮身人面像中,当与拿破仑延伸相结合时,这也非常有效。有关文档的更多示例,请参阅extension's doc

PyCharm's manual的注释部分,开发者给出了一个很好的提示:

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

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

在python中

type([1,2,3]) == type(['a', 'b', 'c'])

您还可以将字符串添加到int列表中。

因此,为了实现PyCharm,在将其作为参数传递之前,必须神奇地检查整个代码中添加到列表中的内容。

你可以看看这个问题Python : define a list of a specific type of object

但是,数组模块只允许“基本值”。

我在这里能想到的唯一解决方案是创建自己的类,扩展python列表“FoodsList”,它可以在添加元素之前检查类型。

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

class FoodsList(list):
    #you can optionally extend append method here to validate type
    pass

def eat(foods):
    """
    :type foods: FoodsList
    """
    energy = 0
    for food in foods:
        energy += food.calories
    return energy


list = FoodsList()
list.append(Food(3))
list.append(Food(4))
print eat(list)

相关问题 更多 >