这些表达式的计算结果应该不同吗?
在我发现代码中的错误之前,我有点困惑。我不得不更改
a.matched_images.count #True when variable is 0
为
a.matched_images.count > 0 #False when variable is 0
因为我很快想知道一个对象是否有任何图像,所以第一个代码将显示为照片有图像,因为当含义确实为 false 时,表达式的计算结果为 True
(“没有图片”/ 0 图片)
我是否正确理解了这一点?如果这些表达式应计算为不同的值,您能否回答或评论。
I was somewhat confused until I found the bug in my code. I had to change
a.matched_images.count #True when variable is 0
to
a.matched_images.count > 0 #False when variable is 0
Since I quickly wanted to know whether an object had any images, the first code will appear like the photo has images since the expression evaluates to True
when the meaning really is false ("no images" / 0 images)
Did I understand this correctly and can you please answer or comment if these expressions should evaluate to different values.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
count
的本质是什么?如果它是一个基本的 Python 数字,则if count
与if count != 0
相同。另一方面,如果count
是自定义类,那么它需要为 Python 2.x 实现__nonzero__
或__len__
,或者对于 Python 3.x,为 >__bool__
或__len__
。如果未定义这些方法,则该类的每个实例都被视为True
。What is the nature of
count
? If it's a basic Python number, thenif count
is the same asif count != 0
. On the other hand, ifcount
is a custom class then it needs to implement either__nonzero__
or__len__
for Python 2.x, or__bool__
or__len__
for Python 3.x. If those methods are not defined, then every instance of that class is consideredTrue
.如果不知道
count
是什么,就很难回答,但是Without knowing what
count
is, it's hard to answer, but this excerpt may be of use to you:.所以..不,如果它是一个 int 那就没关系了。请进行一些跟踪,打印出
count
实际是什么。So.. no, if it were an int that wouldn't matter. Please do some tracing, print out what
count
actually is.