python - If not (variable) 和 if (variable) == false 有什么区别?
问题描述
我正在学习 Python,我刚开始用布尔值学习条件
我对“如果不是”的具体主题感到非常困惑。有人可以向我解释一下:
x = False
if not x:
print("hello")
if x == False:
print("hello")
在 Python 编译器上测试此代码时,我收到两次“hello”。我可以假设这意味着它们对计算机都意味着同样的事情。
有人可以向我解释为什么有人会使用一种方法而不是另一种方法吗?
解决方案
这取决于™。Python 不知道它的任何操作符应该做什么。它调用对象的魔术方法并让它们决定。我们可以通过一个简单的测试看到这一点
class Foo:
"""Demonstrates the difference between a boolean and equality test
by overriding the operations that implement them."""
def __bool__(self):
print("bool")
return True
def __eq__(self, other):
print("eq", repr(other))
return True
x = Foo()
print("This is a boolean operation without an additional parameter")
if not x:
print("one")
print("This is an equality operation with a parameter")
if x == False:
print("two")
生产
This is a boolean operation without an additional parameter
bool
This is an equality operation with a parameter
eq False
two
在第一种情况下,python 通过调用 进行布尔测试__bool__
,在第二种情况下,通过调用__eq__
. 这意味着什么取决于班级。它通常很明显,但像熊猫这样的东西可能会变得棘手。
通常not x
比它更快,x == False
因为__eq__
操作员通常会在确定之前进行第二次布尔比较。在您的情况下,当x = False
您处理用 C 编写的内置类时,它的两个操作将是相似的。但是,x == False
比较需要对另一方进行类型检查,因此会慢一些。
推荐阅读
- grafana - 使用 prometheus 和 grafana 跟踪事件
- c++ - 为什么我的 C++ 程序输出不同的数字来将米转换为英尺?
- android - GPS追踪器android线程
- python - 通用日志记录函数包装器
- python - 如何使用复式表在 3D 中绘图 - Matplotlib
- operating-system - OS:交换空间,数据何时存储在交换空间中?
- reactjs - componentWillReceiveProps 未在 Office 面板上触发
- ios - 根据标志决定是否发送 Crashlytics (Apple) 报告
- python - 关于通过循环脚本循环多个站点的最佳意见
- asp.net - AspNetCore Angular 6.0 SPA 模板中的未知选项 --extractCss