2014-01-08 20 views
-2

我想不通爲什麼:爲什麼Python中的函數是錯誤的?

f = lambda x: x 
In [8]: f is True 
Out[8]: False 

In [9]: not f is True 
Out[9]: True 

In [10]: f is False 
Out[10]: False 

In [11]: f is True 
Out[11]: False 

In [12]: not f 
Out[12]: False 

In [13]: not f is True 
Out[13]: True 

In [14]: not f is False 
Out[14]: True 

確定。所以直到現在我們可以想象這是由於使用「is」而不是「==」。如下所示:

In [15]: 0.00000 is 0 
Out[15]: False 

In [16]: 0.00000 == 0 
Out[16]: True 

好的。但是,爲什麼那麼,如果我做它的功能:

In [17]: not f == False 
Out[17]: True 

In [18]: not f == True 
Out[18]: True 

In [19]: f ==True 
Out[19]: False 

In [20]: f ==False 
Out[20]: False 

In [21]: f 
Out[21]: <function __main__.<lambda>> 

我試圖把它解釋爲因「是」,而不是「==」的例子,但19和20粉碎了我的邏輯。有人可以解釋嗎?

+1

這是特定的功能呢?其他值與True和False相比如何? –

+0

awww很愚蠢。忘了使用bool()比較布爾值。當然 。請刪除 – deddu

回答

1

==檢查equivelency ... is檢查身份...... 功能是爲非falsey價值但並不equivelent爲True

def xyz(): 
    pass 

if xyz: 
    #this will trigger since a method is not a falsey value 

xyz == True #No it is not equal to true 
xyz == False #no it is not equal to false 

xyz is True #no it certainly is not the same memory location as true 
xyz is False #no it is also not the same memory location as false 
5

is測試對象身份。比較Trueis True之外的任何內容都是錯誤的。

您的下一組測試是否測試not (f == False)not (f == True);再次,布爾對象只對自己進行測試,因此與== False比較時,False以外的任何內容都將被測試爲false。 not False然後是真的。

你想用bool(),而不是測試,如果事情是真的還是假的:

>>> bool(f) 
True 
>>> bool(0) 
False 

不要用平等的測試,看看如果事情是真的還是假的。

請注意,只有數字0,空容器和字符串以及False在Python中被認爲是錯誤的。默認情況下,其他所有內容在布爾上下文中都被視爲true。自定義類型可以實現__nonzero__ method(數字時)或__len__ method(實現容器)以更改該行爲。 Python 3用__bool__ method替換了__nonzero__

函數沒有__nonzero____len__方法,所以它們總是被認爲是真的。

+0

你的第一個陳述說「真實是真的」總是會成爲「假」。爲什麼?我希望它是「真實的」,我的口譯員也同意。 –

+0

我知道你在說什麼,但從字面上看,「除了」True is True「之外的任何內容都可能被誤解(例如,意味着」False is False「將是錯誤的)。 – NPE

+0

@Noufal易卜拉欣你錯過了'除了'以外的任何東西...... –

0

你自己的例子顯示f is False是錯誤的,所以我很困惑你的頭銜。

爲什麼你會期望一個函數評估等於兩個布爾值?這不是那種奇怪的行爲嗎?

+0

如果你忘記了一些括號。 '如果char.isdigit和char在['1','2']'vs'中如果char.isdigit()和char在['1','2']' – deddu

2

如果你檢查一個函數的「真實性」,你會看到它是真的。

>>> f = lambda x: x 
>>> bool(f) 
True 

你是函數本身只是比較TrueFalse它永遠不會,因爲它是一個函數。

相關問題