2014-01-08 41 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它永远不会,因为它是一个函数。

相关问题