3 回答

TA貢獻1793條經驗 獲得超6個贊
你可以這樣做。
from typing import TypeVar
# We define T as a TypeVar bound to the base class GenericCopyable
T = TypeVar('T', bound='GenericCopyable')
class GenericCopyable:
# we return the type T of the type of self
# Basically returning an instance of the calling
# type's class
def copy(self: T) -> T:
return type(self)()
class CopyableFoo(GenericCopyable):
pass
foo = CopyableFoo()
bar = foo.copy()
print(bar)
這看起來有點笨拙,因為通常我們不需要注釋self,因為它隱式地是它所綁定的類的類型。不過,mypy 似乎對此沒問題。

TA貢獻1777條經驗 獲得超10個贊
一種可能的解決方案是重寫子類中的方法,然后使用指定其實例的返回類型的子類方法調用超類方法。
class GenericCopyable:
def copy(self) -> GenericCopyable:
... # whatever is required to copy this
class CopyableFoo(GenericCopyable):
def copy(self)->CopyableFoo:
return super().copy()
另一種可能的解決方案是使用輸入模塊導入 Union。這指定父類中的函數能夠返回多種類型
from typing import Union
class GenericCopyable:
def copy(self) -> Union[GenericCopyable,CopyableFoo]:
... # whatever is required to copy this
class CopyableFoo(GenericCopyable):
#Call parent class method directly
GenericCopyable.copy()

TA貢獻1865條經驗 獲得超7個贊
從 Python 3.11 開始,標準庫包含一個顯式的特殊類型 -?Self。
請注意,上面引用的文檔明確提到了這一點。
基類Self
可以這樣寫:
from typing import Self
class GenericCopyable:
? ? def copy(self) -> Self:
? ? ? ? ...
這向類型檢查器指定, 的任何實例都GenericCopyable從其方法返回與其自身類型相同的實例copy()。
添加回答
舉報