gpt4 book ai didi

python - If not (variable) 和 if (variable) == false 有什么区别?

转载 作者:行者123 更新时间:2023-12-05 01:07:08 25 4
gpt4 key购买 nike

我正在学习 Python,我刚刚开始学习使用 bool 值的条件

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

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__ 进行 bool 测试,在第二种情况下,通过调用 __eq__ 进行相等性测试。这意味着什么取决于类(class)。它通常很明显,但像 pandas 这样的东西可能会变得棘手。

通常 not xx == False 快,因为 __eq__ 运算符通常会在确定之前进行第二次 bool 比较.在您的情况下,当 x = False 您正在处理用 C 编写的内置类时,它的两个操作将是相似的。但是,x == False 比较还是需要对对方进行类型检查,所以会慢一些。

关于python - If not (variable) 和 if (variable) == false 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67793833/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com