3 回答
![?](http://img1.sycdn.imooc.com/545867790001599f02200220-100-100.jpg)
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 似乎对此没问题。
![?](http://img1.sycdn.imooc.com/5458622b000117dd02200220-100-100.jpg)
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()
![?](http://img1.sycdn.imooc.com/54584ef20001deba02200220-100-100.jpg)
TA贡献1865条经验 获得超7个赞
从 Python 3.11 开始,标准库包含一个显式的特殊类型 - Self。
请注意,上面引用的文档明确提到了这一点。
基类Self
可以这样写:
from typing import Self
class GenericCopyable:
def copy(self) -> Self:
...
这向类型检查器指定, 的任何实例都GenericCopyable从其方法返回与其自身类型相同的实例copy()。
添加回答
举报