这些表达式的计算方式是否应该不同?

2024-04-26 20:36:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有点困惑,直到我发现我的代码中的错误。我得换衣服

a.matched_images.count #True when variable is 0

a.matched_images.count > 0 #False when variable is 0

因为我很快就想知道一个对象是否有任何图像,所以第一个代码将显示为photo has images,因为表达式的计算结果是True,而实际意义是false(“no images”/0 images)

我是否正确地理解了这一点,您能否回答或评论这些表达式是否应计算为不同的值。你知道吗


Tags: 对象代码图像falsetrueis表达式count
3条回答

什么是count的本质?如果它是一个基本的Python编号,那么if countif count != 0相同。另一方面,如果count是一个自定义类,那么它需要为Python2.x实现__nonzero____len__,或为Python3.x实现__bool____len__。如果没有定义这些方法,那么该类的每个实例都被视为True。你知道吗

如果不知道count是什么,很难回答,但是this excerpt可能对你有用你:。你知道吗

The following values are considered false:

  • None

  • False

  • zero of any numeric type, for example, 0, 0L, 0.0, 0j.

  • any empty sequence, for example, '', (), [].

  • any empty mapping, for example, {}.

  • instances of user-defined classes, if the class defines a __nonzero__() or __len__() method, when that method returns the integer zero or bool value False. [1]

All other values are considered true — so objects of many types are always true.

>>> bool(0)
False

所以。。不,如果是int,那就不重要了。请做一些追踪,打印出count实际上是什么。你知道吗

相关问题 更多 >