風格指南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