有什么区别?
myVar: myCustomClassType
对比
myVar: myCustomClassType = None
我问是因为 Pycharm 检查员对后者尖叫:
Expected type 'myCustomClassType', got 'None' instead
我知道 None 也是一个对象,因此这次检查表明存在类型冲突。 我的问题是哪种形式更好?
请您参考如下方法:
第一个是Variable Annotation的例子,您可以在其中使用类型提示让类型检查器知道将标识符(在特定范围内)与某种类型相关联。
两者的区别在于
myVar: myCustomClassType
不为 myVar 赋值,而第二个赋值。如果你想让 myVar 有一个 None 值或一个 myCustomClassType 值,你应该使用 Optional typing 模块的通用类型:
from typing import Optional
myVar: Optional[myCustomClassType]
如果您的变量应该只包含 myCustomClassType 值,那么您应该使用第一个变体,并确保在使用它之前分配一个值。
