簡體   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