gpt4 book ai didi

Python:测试无,测试 bool 值

转载 作者:太空狗 更新时间:2023-10-29 18:24:41 26 4
gpt4 key购买 nike

这些方法之间是否存在任何低级别的、与实现相关的差异(性能方面的差异)?

# check if string is empty
# the preferred way it seems [1]
if string:
print string
else:
print "It's empty."

# versus [2]
if string is '':

# or [3]
if string == '':

例如,当测试 None 时,我仍然发现它更具可读性和明确性:

if some_var is not None:

..而不是..

if not some_var:

if not some_var,至少对我来说,总是读作“if some_var does not exist”。

哪个更好用,==is 和 bool-testing 的正确用例是什么?

最佳答案

切勿使用 is 进行(值)相等性测试。只用它来测试对象身份。它可能适用于 if string is '' 示例,但这取决于实现,您不能依赖它。

>>> a = "hi"
>>> a is "hi"
True
>>> a = "hi there!"
>>> a is "hi there!"
False

除此之外,使用最能传达代码含义的内容。

我更喜欢较短的 if string:,但 if string != '': 可能更明确。

再一次 if variable: 适用于所有类型的对象,因此如果 variable 不限于一种类型,这比 if variable 更好! = ""和变量 != 0:

关于Python:测试无,测试 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7038681/

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