为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

忽然笑 2023-09-12 17:27:51
假设我有这些课程:class GenericCopyable:    def copy(self) -> GenericCopyable:        ... # whatever is required to copy thisclass 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在我的“真实”程序中,这会困难得多。
查看完整描述

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 似乎对此没问题。


查看完整回答
反对 回复 2023-09-12
?
不负相思意

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()


查看完整回答
反对 回复 2023-09-12
?
鸿蒙传说

TA贡献1865条经验 获得超7个赞

从 Python 3.11 开始,标准库包含一个显式的特殊类型 - Self。

请注意,上面引用的文档明确提到了这一点。

基类Self可以这样写:

from typing import Self


class GenericCopyable:

    def copy(self) -> Self:

        ...

这向类型检查器指定, 的任何实例都GenericCopyable从其方法返回与其自身类型相同的实例copy()。


查看完整回答
反对 回复 2023-09-12
  • 3 回答
  • 0 关注
  • 123 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信