You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python类型提示问题:子类无法作为父类列表输入

问题描述

编写了如下代码,希望将父类Product的子类Food、Drink传入声明为List[Product]类型参数的ShoppingBasket构造方法中:

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)

但VS Code的Pylance工具提示错误:

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并非正式的抽象类,需要消除该错误提示。

错误原因
  1. 参数标注逻辑错误:*items: List[Product]写法有误——*items表示接收多个独立的位置参数,每个参数的类型应该是单个元素,而非List类型;
  2. 传入值与标注不匹配:代码中传入的是Food、Drink类本身(属于Type[Product]类型),但标注要求的是List[Product],类型完全不兼容。
解决方案

根据实际需求选择以下两种修正方式:

方式一:传入Product子类的实例(符合购物篮语义)

如果购物篮的设计目的是存放商品实例,修改参数标注为Product,并传入类的实例对象:

from typing import List

class Product:
    pass

class Food(Product):
    pass

class Drink(Product):
    pass

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

# 传入类的实例而非类本身
basket = ShoppingBasket(Food(), Drink())
print(basket.items)

方式二:传入Product子类的类对象

如果确实需要传入类本身,需导入Type并修正参数标注:

from typing import List, Type

class Product:
    pass

class Food(Product):
    pass

class Drink(Product):
    pass

class ShoppingBasket:
    # 标注为接收多个Product子类的类对象
    def __init__(self, *items: Type[Product]):
        self.items = items

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

内容的提问来源于stack exchange,提问作者Weholt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 09:06:30