【发布时间】:2023-02-24 02:46:33
【问题描述】:
例如,我有两个类:Animal 和Cat。
class Animal:
pass
class Cat(Animal):
pass
然后,我想做一个Animal的列表,这样我就可以写一些函数来管理这个Animal的列表。在这里创建一个继承list的类是很直观的。
from typing import List
class AnimalList(List[Animal]):
def get_element(self) -> Animal: # get one element, just for example
return self[0]
(看过this等问题,我觉得继承list很可能是我想要的,而不是创建一个以list为属性的类。)
之后,我发现我还需要一个类,这样我就可以管理一个Cat的列表。 Cat 有一些它的基础 Animal 没有的功能。所以,我需要AnimalList 中的函数和只能通过Cat 列表完成的特殊函数。也就是说,我需要一个满足以下要求的类CatList:
- 我可以管理
Cat的列表,就像我管理list一样。例如,我可以这样做:# I want to do something like: cat = Cat() cat_list = CatList() cat_list.append(cat) # manipulate this CatList like list cat_1 = cat_list[0]-
CatList可以继承AnimalList中的方法,也有自己的方法。例如,我可以这样做:
# I want to do something like: cat_list.play_with_cats() # Own function cat_2 = cat_list.get_element() # Base function-
CatList.__getitem__()(上面的cat_1)的类型提示是Cat -
CatList.get_element()(上面的cat_2)等基类方法的结果类型提示是Cat
问题: 如何创建满足上述要求的类
CatList?CatList应该继承的类是什么?我已经尝试了几种方法来做到这一点。
尝试 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()但我需要重写
__getitem__()、get_element()等所有函数,以确保这些函数对应的类型提示是Cat。这太麻烦了。尝试 2
继承
List[Cat]和AnimalList:class CatList(List[Cat], AnimalList): def play_with_cats(self) -> None: print("Play with cats!")但是
CatList.__getitem__()和get_element()结果的类型提示变为Any,而不是Cat。 -
【问题讨论】:
-
尚未在 Python 中使用它,但您可能有兴趣查看 Python's Generics 以帮助解决此问题。
标签: python list inheritance type-hinting