风格指南http://www.python.org/dev/peps/pep-0008为什么没有真正的==真:
的最后一个点读...
布尔值,不要比较,真或假使用==。
为什么?
编辑 只是要清楚什么IM要求(和它的指示问题本身的),当你写
if something:
print "something is true"
你正在做一个隐式转换为布尔值可能会或可能不会根据工作关于什么是真正意义。恕我直言,这种形式的编程是不鼓励的,因为它可能导致的副作用。
numberOfApples = -1
if numberOfApples:
print "you have apples" # is not what is intended.
if numberOfApples == True:
print "you have apples" # is also not what is intended.
iHaveApples = numberOfApples > 0
if iHaveApples is True: # Edit: corrected this.. the "is" is better than the ==
print "you have apples" # is correct.
隐式转换会掩盖逻辑错误。那么为什么风格指南鼓励这个呢?
我开始认为布尔测试的最佳样式被标记为样式指南中最差的样式。 如果numberOfApples为True: 将清除numberOfApples不是一个布尔值。 – 2012-04-19 19:40:06
那么你真正想要的是比较如果x是bool()类型,如果它是,如果它是真或假 – 2012-04-22 16:50:47
@PedroWerneck正确。因此,风格指南错误地说,测试bool的最糟糕的方式是如果bool_type是[True | False]:因为它实际上是最好的方式 – 2012-04-23 14:55:33