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,它似乎可以正常工作。谢谢你提供的信息,我已经编辑了答案。