2016-04-21 120 views
0

有人可以澄清這些賦值語句背後的邏輯。Python布爾邏輯混淆

>>> True 
True 
>>> True = False 
>>> True 
False 
>>> True = True 
>>> True 
False 
>>> a = True 
>>> if a: 
...  print "a is True" 
... else: 
...  print "a is False" 
... 
a is False 

根據手冊,類布爾的僅兩個實例是TrueFalse

Help on bool object: 

True = class bool(int) 
| bool(x) -> bool 
| 
| Returns True when the argument x is true, False otherwise. 
| The builtins True and False are the only two instances of the class bool. 
| The class bool is a subclass of the class int, and cannot be subclassed. 
| 
| Method resolution order: 
|  bool 
|  int 
|  object 

所以我重寫默認實例?如果是這樣,爲什麼python不會將True指定爲下面賦值中的默認實例?我如何在下面的語句中指定默認的python True

>>> True = False 
>>> True 
False 
>>> True = True 
>>> True 
False  #why? 

在此先感謝您的幫助!

+1

Python 3標籤在這裏是不相關的:[爲什麼True和False更改爲Python 3中的關鍵字](http://stackoverflow.com/questions/18050815/why-were-true-and-false-changed -python-3) – soon

+0

用'=='完成比較。 – RemcoGerlich

+0

@RemcoGerlich Soory愚蠢的錯誤! –

回答

0

當你這樣做:

True = False 

True成爲False ..當你這樣做:

True = True 

這就像寫:

True = False 

如果你想它「原」True再次,你應該:

>>> True = not True # recall that you assigned False to True 
>>> True 
True 
+0

'del True'是刪除名爲'True'的局部變量的一種更好的方法,使內建變量再次可見。 – RemcoGerlich

+0

我們如何訪問python中內置的True?看起來你正在對你的答案的局部變量'True'進行'not'操作... –

+0

@HiteshPaul它將成爲「內置」'True'。 – Maroun