首页 > 解决方案 > If not (variable) 和 if (variable) == false 有什么区别?

问题描述

我正在学习 Python,我刚开始用布尔值学习条件

我对“如果不是”的具体主题感到非常困惑。有人可以向我解释一下:

x = False

if not x:
   print("hello")

if x == False:
   print("hello")

在 Python 编译器上测试此代码时,我收到两次“hello”。我可以假设这意味着它们对计算机都意味着同样的事情。

有人可以向我解释为什么有人会使用一种方法而不是另一种方法吗?

标签: pythonif-statementconditional-statements

解决方案


这取决于™。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比较需要对另一方进行类型检查,因此会慢一些。


推荐阅读