gpt4 book ai didi

Python:将空字符串与 False 进行比较是 False,为什么?

转载 作者:太空宇宙 更新时间:2023-11-03 12:27:08 25 4
gpt4 key购买 nike

如果 not '' 的计算结果为 True,为什么 '' == False 的计算结果为 False

例如,与 False 比较时,其他类型(例如 0、0.0)的“voids”将返回 True:

>>> 0 == False
True
>>> 0.0 == False
True

谢谢

最佳答案

In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. User-defined objects can customize their truth value by providing a __bool__() method.

The operator not yields True if its argument is false, False otherwise.

https://docs.python.org/3/reference/expressions.html#comparisons

但是:

The operators <, >, ==, >=, <=, and != compare the values of two objects. The objects do not need to have the same type.

...

Because all types are (direct or indirect) subtypes of object, they inherit the default comparison behavior from object. Types can customize their comparison behavior by implementing rich comparison methods like __lt__() ...

https://docs.python.org/3/reference/expressions.html#boolean-operations

因此,技术实现答案是它的行为方式是因为 not==使用不同的比较。 not使用 __bool__ ,对象的“真值”,而==使用 __eq__ ,一个对象与另一个对象的直接比较。因此,可以询问一个对象是否认为自己是 truthyfalsey,并与此分开询问它是否认为自己与另一个对象相等。默认实现的安排方式是两个对象都可以认为自己是 falsey 但不认为自己彼此相等。

关于Python:将空字符串与 False 进行比较是 False,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38972645/

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