我有一个泛型类,带有一个
next
方法,该方法返回参数化为差异类型变量的自身实例。
我可以使用
next
来指定 "
方法的返回类型来引用类本身:
DataIn = TypeVar('DataIn')
DataOut = TypeVar('DataOut')
@dataclass
class Msg(Generic[DataIn]):
source: str
data: DataIn
def next(self, data: DataOut) -> "Msg[DataOut]":
"""
Create a new message with the same source but different data
"""
return Msg(source=self.source, data=data)
我想使用 PEP 673
Self
类型以避免 "
':
def next(self, data: DataOut) -> Self[DataOut]:
但是无法在 Pylance / Pyright 中输入检查:
Expected no type arguments for class "Self"
文档说:“Self也可以在泛型类方法中使用”,但没有显示这个特定的用例。
支持吗?
这是不支持的,而且不是故意支持的。对于泛型类型,
Self
(在常规方法中 - 不是类方法)指的是一些已经参数化的实例。
引用您链接的文档(甚至同一部分):
请注意,我们拒绝将
与类型参数一起使用,例如Self
。这是因为它造成了 self 参数类型的歧义并引入了不必要的复杂性:Self[int]
class Container(Generic[T]):
def foo(
self, other: Self[int], other2: Self,
) -> Self[str]: # Rejected
...
在这种情况下,我们建议为 self 使用显式类型:
class Container(Generic[T]):
def foo(
self: Container[T],
other: Container[int],
other2: Container[T]
) -> Container[str]: ...