亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何輸入提示返回當前類實例的函數?

如何輸入提示返回當前類實例的函數?

忽然笑 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 關注
  • 151 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號