如何输入提示返回当前类实例的函数?

假设我有这些课程:


class GenericCopyable:

    def copy(self) -> GenericCopyable:

        ... # whatever is required to copy this


class CopyableFoo(GenericCopyable):

    ... # uses the parent implementation of "copy"

    def bar(self): …


def some_code(victim: CopyableFoo):

    v = victim.copy()

    v.bar()  ### I know that this works because "v" is a CopyableFoo, but mypy doesn't

问题是我需要的返回类型是CopyableFoo.copy()to CopyableFoo,而不是GenericCopyable。


那可能吗?


编辑:以上是说明问题的示例代码。在这个例子中,以某种方式修改some_code或当然是可能的;CopyableFoo在我的“真实”程序中,这会困难得多。


忽然笑
浏览 124回答 3
3回答

摇曳的蔷薇

你可以这样做。from typing import TypeVar# We define T as a TypeVar bound to the base class GenericCopyableT = 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):    passfoo = CopyableFoo()bar = foo.copy()print(bar)这看起来有点笨拙,因为通常我们不需要注释self,因为它隐式地是它所绑定的类的类型。不过,mypy 似乎对此没问题。

不负相思意

一种可能的解决方案是重写子类中的方法,然后使用指定其实例的返回类型的子类方法调用超类方法。class GenericCopyable:    def copy(self) -> GenericCopyable:        ... # whatever is required to copy thisclass CopyableFoo(GenericCopyable):   def copy(self)->CopyableFoo:       return super().copy()另一种可能的解决方案是使用输入模块导入 Union。这指定父类中的函数能够返回多种类型from typing import Unionclass GenericCopyable:    def copy(self) -> Union[GenericCopyable,CopyableFoo]:        ... # whatever is required to copy thisclass CopyableFoo(GenericCopyable):    #Call parent class method directly    GenericCopyable.copy()

鸿蒙传说

从 Python 3.11 开始,标准库包含一个显式的特殊类型 - Self。请注意,上面引用的文档明确提到了这一点。基类Self可以这样写:from typing import Selfclass GenericCopyable:    def copy(self) -> Self:        ...这向类型检查器指定, 的任何实例都GenericCopyable从其方法返回与其自身类型相同的实例copy()。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python