繁体   English   中英

子类作为 python 中超类/类型提示列表的输入无效

[英]Subclass not valid as input to list of Superclass / type hinting in python

我有这段代码,我想将抽象 class 的子类添加到项目列表中,指定为超类的列表:

from typing import List

class Product:
    pass

class Food(Product):
    pass

class Drink(Product):
    pass

class ShoppingBasket:
    def __init__(self, *items: List[Product]):
        self.items = items

basket = ShoppingBasket(Food, Drink)
print(basket.items)

但 Visual Studio Code 对代码的分析以 Food and Drink 参数下的波浪线结束,并带有以下文本:

Argument of type "Type[Food]" cannot be assigned to parameter "items" of type "List[Product]" in function "__init__" "Type[type]" is incompatible with "Type[List[Product]]"PylancereportGeneralTypeIssues"

我知道Product不是一个适当的元类/抽象,但我怎样才能避免这个消息?

对于*args参数的类型提示,您给出单个 arguments 的类型,而不是 arguments 的集合(这将是一个Tuple )。 您还传递了一个类型而不是一个实例,因此您需要像消息中所说的那样适合Type[Food]的东西。

from typing import Type

class Product:
    pass

class Food(Product):
    pass

class Drink(Product):
    pass

class ShoppingBasket:
    def __init__(self, *items: Type[Product]):
        self.items = items

basket = ShoppingBasket(Food, Drink)
print(basket.items)

这对我来说不会产生 mypy 错误。

暂无
暂无

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

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