如何為專門的(typing
有意義的)類提供不同的定義?
示例,為什么這可能有用:
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)
uj5u.com熱心網友回復:
實際上有一種方法可以做到這一點,但不是創建一個類的“特化”,而是需要在類定義中定義一個類的所有方法(如果沒有型別注釋,這就是 Python 的樣子),并添加一個方法引數的型別約束self
:
class Collection(Generic[T]):
def sum(self: "Collection[int]") -> int:
...
a = C[int]([1, 2, 3])
reveal_type(a.sum()) # int
b = C[str](["a", "b", "c"])
reveal_type(b.sum()) # error: Invalid self argument "C[str]" to attribute function "sum"
請參閱mypy-play上的具體示例。
請注意,這僅適用于具體型別,不適用于型別變數。如果您將 a 替換int
為TypeVar
帶邊界 ( TypeVar("T", bound=numbers.Real)
) 或約束 ( TypeVar("T", int, float)
),mypy 似乎會忽略它們并接受任何型別。這也在上面的例子中得到了證明。我相信這是一個錯誤或疏忽。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/470428.html
上一篇:如何實作泛型介面?
下一篇:switch陳述句中的泛型型別