Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 键入父类的方法_Python - Fatal编程技术网

Python 键入父类的方法

Python 键入父类的方法,python,Python,我的父类继承了list,并添加了一些方法,这些方法返回列表中的项。我的子类是一系列对象(都是相同类型的)。如何键入提示子类(Inventory)告诉类型检查器(例如PyCharm)filter方法返回一系列Car对象 我在下面重写了我的代码摘录。希望我没有过分简化这个例子 from dataclasses import dataclass class DB(list): def filter(self, **kwargs): """Ret

我的父类继承了
list
,并添加了一些方法,这些方法返回列表中的项。我的子类是一系列对象(都是相同类型的)。如何键入提示子类(
Inventory
)告诉类型检查器(例如PyCharm)filter方法返回一系列
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:如何在类之外键入提示类方法。

DB
需要是泛型的,这样才能起作用,而不是:

类数据库(列表):。。。
应该是:

输入import TypeVar
T=TypeVar('T')
类DB(列表[T]):。。。
编辑:
在Python3.5-3.8中,您不能执行
list[t]
,因此您可以执行以下操作:

输入import TypeVar,List
T=TypeVar('T')
类DB(列表[T]):。。。

谢谢@ChaimG的建议。

您有权访问
DB
课程吗?也就是说,你能改变定义它的代码吗?@Roy Cohen:yes写一些类似
T=typing.TypeVar('T');类DB(list[T]):…
(我对python类型的提示了解不多,所以这可能不起作用,但请尝试一下)。@RoyCohen:哇,它很管用!太棒了。这与Python3.9中的工作原理一样。对于Python3.5-3.8,使用
键入.List[T]
而不是
List[T]
@ChaimG,这需要从
List
独立地进行子类化吗?例如,
class DB(键入.List[T],List):…
如果没有
List
@ChaimG,它似乎可以正常工作。谢谢你提供的信息,我已经编辑了答案。