Как предоставить другое определение специализированному (в смысле типизации) классу?
Пример, почему это может быть полезно:
TElement = TypeVar('TElement')
class BaseCollection(Generic[TElement]):
name: str
data: List[TElement]
def __add__(self, other: 'BaseCollection[TElement]'):
return CombinedCollection[TElement].from_collections(self, other)
...
class Collection(BaseCollection):
pass
# how do I do this specialization
class Collection[int](BaseCollection[int]):
def sum(self):
return sum(self.data)
# so that CombinedCollection[int] has also the sum method
class CombinedCollection(Collection[TElement]):
@classmethod
def from_collections(cls, *lists: Collection[TElement]):
return CombinedCollection[TElement]('(' + '+'.join(l.name for l in lists) + ')',
[x for l in lists for x in l])
# i.e. I can do
c = Collection[int]('my_collection c', [1,2])
d = Collection[int]('my_collection d', [-1, -2, -3])
cd = c + d
# and now I can do this:
cd.sum()
# -3
cd.name
# (my_collection c+my_collection d)
Подробнее здесь: https://stackoverflow.com/questions/720 ... g-generics
Как специализировать класс на Python (обобщенные наборы типов) ⇐ Python
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение