我有一个数据类,如下所示

@dataclass
class DataObj:
    """ DataObj creates an object for each record in data
    """
    name: str
    profit: int
    space: float

我有另一个容器类,它保存上述类的对象

class DataContainer:
    """ Data Container class holding objects of DataObj class
    """
    def __init__(self, data_tuple_list: List[Tuple[str, int, float]]) -> None:
        self.container = []
        for data_tuple in data_tuple_list:
            self.container.append(DataObj(*data_tuple))

    def __getitem__(self, n: int) -> Type[DataObj]:
        return self.container.__getitem__(n)

然而,当我使用mypy判断代码时,我得到了以下错误

error: Incompatible return value type (got "DataObj", expected "Type[DataObj]")
Found 1 error in 1 file (checked 1 source file)

我的python版本是3.8.10.

问题:如何修复错误.

编辑

  1. 如果我用self.container: List[DataObj] = [],我得到error: Incompatible return value type (got "DataObj", expected "Type[DataObj]") Found 1 error in 1 file (checked 1 source file)
  2. 如果我用self.container: List[Type[DataObj]] = [],我得到error: Argument 1 to "append" of "list" has incompatible type "DataObj"; expected "Type[DataObj]" Found 1 error in 1 file (checked 1 source file).

推荐答案

可能您没有键入hint您的容器(self.container),所以mypy将其视为List[Any],并且可能看不到它只包含DataObj类型的值,因此当您从列表中返回某个值时,mypy无法确定它是DataObj类型的

try :


class DataContainer:
    """ Data Container class holding objects of DataObj class
    """
    def __init__(self, data_tuple_list: List[Tuple[str, int, float]]) -> None:
        self.container: List[DataObj] = []
        for data_tuple in data_tuple_list:
            self.container.append(DataObj(*data_tuple))

    def __getitem__(self, n: int) -> Type[DataObj]:
        return self.container.__getitem__(n)

EDIT

这是我try 过的,它对我很有效:

from dataclasses import dataclass
from typing import List, Tuple


@dataclass
class DataObj:
    """ DataObj creates an object for each record in data
    """
    name: str
    profit: int
    space: float


class DataContainer:
    """ Data Container class holding objects of DataObj class
    """

    def __init__(self, data_tuple_list: List[Tuple[str, int, float]]) -> None:
        self.container = []
        for data_tuple in data_tuple_list:
            self.container.append(DataObj(*data_tuple))

    def __getitem__(self, n: int) -> DataObj:
        return self.container.__getitem__(n)

if __name__ == '__main__':
    data_tuple_list_concrete = [
        ('test1', 1, 1.1),
        ('test2', 2, 2.2),
        ('test3', 3, 3.3),
        ('test4', 4, 4.4),
        ('test5', 5, 5.5),
    ]

    dc = DataContainer(data_tuple_list_concrete)
    print(dc[0])
    print(dc[1])
    print(dc[2])
    print(dc[3])
    print(dc[4])

"""
Output:

DataObj(name='test1', profit=1, space=1.1)
DataObj(name='test2', profit=2, space=2.2)
DataObj(name='test3', profit=3, space=3.3)
DataObj(name='test4', profit=4, space=4.4)
DataObj(name='test5', profit=5, space=5.5)
"""
$ mypy main.py
Success: no issues found in 1 source file

Python相关问答推荐

用SymPy在Python中求解指数函数

Beautifulsoup:遍历一个列表,从a到z,并解析数据,以便将其存储在pdf中.

在Python中控制列表中的数据步长

如何为需要初始化的具体类实现依赖反转和接口分离?

如何从数据框列中提取特定部分并将该值填充到其他列中?

在round函数中使用列值

将像素信息写入文件并读取该文件

Django更新视图未更新

有什么方法可以在不对多索引DataFrame的列进行排序的情况下避免词法排序警告吗?

如何让doctest在mkdocs的标记代码块中运行示例?

在伪子进程中模拟标准输出.打开

如何使用Pillow基于二进制掩码设置PNG的RGB值

解析PANAS中某列中时间戳格式可变的时间戳列

Python:比较日期并批量更新某些字段

在给定一组约束的情况下使用所有唯一组合创建数据帧

在函数中找不到第一个全局变量,导致错误.第二个全局变量不会导致错误?

生成所有排列:为什么在递归中产生的值不在输出中?

OpenCV发现RGBA图像的轮廓不起作用

WinError 193%1不是有效的Win32应用程序.AZ二头肌

如何在Django中使用使用数学过滤器的If Else条件?