繁体   English   中英

类型提示父 class 的方法

[英]Type hint the methods of a parent class

我的父母 class 继承了list并添加了一些返回列表中项目的方法。 我的孩子 class 是一系列对象(都是同一类型)。 如何键入提示子项 ( Inventory ) class 以告诉类型检查器(例如 PyCharm)过滤器方法返回一系列Car对象?

我在下面重写了我的代码摘录。 希望我没有过度简化这个例子。

from dataclasses import dataclass


class DB(list):
    def filter(self, **kwargs):
        """Returns all matching items in the DB.
        Args:
            **kwargs: Attribute/Value pairs.
        """

        def is_match(item):
            """Do all the attribute/value pairs match for this item?"""
            result = all(getattr(item, k) == v
                         for k, v in kwargs.items())
            return result

        return type(self)(x for x in self if is_match(x))


@dataclass
class Car:
    make: str = 'Tesla'


class Inventory(DB[Car]):
    # Type hint the Inventory class as a sequence of Car objects?
    pass

    # Type hint the parent filter() method???
    filter : (make: str) -> Inventory[Inventory]



inventory = Inventory((Car(), Car('Jaguar')))
inventory[0].make               # Autocomplete is working here.                    
filtered = inventory.filter(model='X')
filtered[0].?                   # Pycharm should know that this is a Car, and autocomplete attributes.

已编辑:-> 库存 [库存] 和格式。

tl; dr:如何在 class 之外键入提示 class 方法。

class DB需要是通用的才能正常工作,而不是:

class DB(list): ...

它应该是:

from typing import TypeVar

T = TypeVar('T')
class DB(list[T]): ...

编辑:
在 python 3.5 - 3.8 你不能做list[T]所以你会这样做:

from typing import TypeVar, List

T = TypeVar('T')
class DB(List[T]): ...

感谢@ChaimG 的建议。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM