我想声明一个实例属性,类型暗示为
float
,初始化时不分配值。该值是在运行时、实例初始化后(也称为
__init__
).
this answer
,我可以将值设置为
None
. 但是,我的IDE(
PyCharm
PyTypeChecker
旗帜,说
Expected type 'float', got type 'None' instead
.
我发现如果将值设置为省略号(建议
this answer
),aka值=
...
,PyCharm不再抱怨了。
这里的最佳做法是什么?
无
...
?
示例代码
class SomeClass:
def __init__(self):
"""Initialize with an unassigned value."""
# PyCharm complains here
self._unassigned_val = None # type: float
# PyCharm doesn't complain here
self._unassigned_val2 = ... # type: float
def called_during_runtime(self) -> None:
"""This gets called after __init__ has run."""
self._unassigned_val = 1.0
self._unassigned_val2 = 1.0
在我的IDE中是什么样子的: