問題描述
我有一個類,我希望屬性的初始值為 None
:
I have a class where I want the initial value of an attribute to be None
:
class SomeClass:
def __init__(self):
self.some_attribute = None
如何添加類型提示,以便 IDE 了解 some_attribute
通常屬于 AnotherClass
類型?
How can I add type hinting, so that the IDE understands that some_attribute
is usually of the type AnotherClass
?
推薦答案
在 Python 3.5 中,你必須寫
In Python 3.5, you have to write
self.some_attribute = None # type: AnotherClass
從 Python 3.6 開始,為變量添加了新的類型提示語法(PEP 526):
Since Python 3.6, new type hinting syntax was added for variables (PEP 526):
self.some_attribute: AnotherClass = None
這可能會讓每個類型檢查系統都抱怨,因為 None 實際上不是 AnotherClass 的實例.相反,您可以使用 typing.Union[None, AnotherClass]
,或簡寫:
This will probably make every type-checking system complain, because None is in fact not an instance of AnotherClass. Instead, you can use typing.Union[None, AnotherClass]
, or the shorthand:
from typing import Optional
...
self.some_attribute: Optional[AnotherClass] = None
這篇關于如何在 Python 3.5 中鍵入提示屬性?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!