[英]Difference between super(Foo, self) and super(Foo, self.__class__)?
[英]When returning an instance of class Foo using self.__class__(), why does PyCharm think the type should be Optional[Type[Foo]]?
我有一個 class Foo ,它有一個返回另一個 Foo 實例的方法。
from __future__ import annotations
class Foo:
def get_other_foo(self) -> Foo:
return self.__class__()
( __future__
導入是為了使方法上的Foo
注釋在 Python 3.7 中工作。)
這可行,並且 MyPy 不會標記文件中的任何錯誤。 但是,PyCharm 以黃色突出顯示返回值,當我在它上面使用 hover 時,我收到警告“預期類型'Foo',改為'Optional [Type [Foo]]'”。
我考慮在方法中對 Foo 進行硬編碼,如下所示:
from __future__ import annotations
class Foo:
def get_other_foo(self) -> Foo:
return Foo()
這也有效,並使 PyCharm 警告靜音。 但是,在子類中,這將返回 Foo 的實例而不是子類的實例,所以我不願意這樣做。
為什么 PyCharm 在我的第一個示例中認為返回類型應該是Optional[Type[Foo]]
? 有沒有辦法修復 PyCharm 警告,同時保持get_other_foo()
從子類調用時返回子類實例的能力?
這是一個已知問題https://youtrack.jetbrains.com/issue/PY-37935 ,請投票!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.