使用相等运算符执行的Pycharm与None的比较

2024-04-24 21:19:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是python3.6和pycharm。在

我的一行代码说:

If oim.sent != None:

Pycharm给出了以下措辞非常强硬的警告:

That type of comparisons should always be done with 'is' or 'is not', never the equality operators.

但是,我使用这一行代码来区分None和{}的值-我这样写这行是正确的,还是说你不应该对None使用相等运算符?在

编辑:

我误解了警告。我想这是在指示我使用if not oim.sent:,当然,它不会区分None和{}-然而,正如答案指出的那样,正确的表达式应该是if oim.sent is not None:


Tags: 代码none警告ifthatistypenot
2条回答

这只是一个警告,因为您没有遵循python准则。你的代码运行正常。如果需要,最好使用:

if oim.sent is not None:

但是,您当然可以使用!= None

if oim.sent is not None:

速度更快,而且是惯用的Python,因此每个人都知道您知道自己在做什么;-)

相关问题 更多 >