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

Python中如何正确继承继承自list的类并实现类型提示

如何实现满足类型提示要求的CatList类

背景

我定义了两个类:Animal和Cat,其中Cat继承自Animal:

class Animal:
    pass


class Cat(Animal):
    pass

为了管理Animal对象的列表,我创建了继承自List[Animal]的AnimalList类,包含自定义方法:

from typing import List


class AnimalList(List[Animal]):
    def get_element(self) -> Animal:  # 获取元素的示例方法
        return self[0]

现在需要一个CatList类来管理Cat对象的列表,它需要满足以下要求:

  • 能像普通list一样操作,比如调用append、通过索引访问元素
  • 继承AnimalList中的所有方法,同时可添加专属方法(如play_with_cats)
  • __getitem__方法返回的元素类型提示为Cat
  • 从AnimalList继承的方法(如get_element)返回值的类型提示也为Cat

已尝试的方案

尝试1:直接继承AnimalList

class CatList(AnimalList):
    def play_with_cats(self) -> None:
        print("Play with cats!")
        
    def __getitem__(self, item) -> Cat:
        return self.__getitem__(item)
    
    def get_element(self) -> Cat:
        return super().get_element()

问题:需要手动重写所有涉及返回类型的方法来修正类型提示,操作繁琐。

尝试2:同时继承List[Cat]和AnimalList

class CatList(List[Cat], AnimalList):
    def play_with_cats(self) -> None:
        print("Play with cats!")

问题:__getitem__和get_element的返回类型提示变为Any,不符合预期。

解决方案:使用泛型基类

正确的做法是将AnimalList定义为泛型类,让CatList指定具体类型参数,自动继承正确的类型提示,无需手动重写方法。

修改后的AnimalList:

from typing import List, TypeVar, Generic

T = TypeVar('T', bound=Animal)  # 限定T必须是Animal的子类

class AnimalList(Generic[T], List[T]):
    def get_element(self) -> T:
        return self[0]

定义CatList:

class CatList(AnimalList[Cat]):
    def play_with_cats(self) -> None:
        print("Play with cats!")

这样实现后:

  1. CatList可像普通列表一样调用append、索引访问等方法,且仅能添加Cat类型对象
  2. 自动继承AnimalList的get_element方法,返回类型提示为Cat
  3. __getitem__的返回类型自动为Cat
  4. 可正常添加自定义的play_with_cats方法

验证代码:

cat = Cat()
cat_list = CatList()
cat_list.append(cat)
cat_1 = cat_list[0]  # 类型提示为Cat
cat_2 = cat_list.get_element()  # 类型提示为Cat
cat_list.play_with_cats()  # 正常执行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 20:09:24