“2+2=5”Python版

2024-04-19 21:45:53 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能解释一下这个棘手的输出:

>>> not(type(1.01)) == type(1) # Why does the expression evaluates to True!?
True
>>> not(type(1.01))
False
>>> False == type(1)
False

那里发生了什么?为什么会这样?在

回答: 当我问这个问题时,我把not当作一个函数,但实际上{}不是函数。这就是为什么not(ţsomething)不会改变操作符的优先级。例如:

^{pr2}$

同:

not(type(1.01) == type(1))

以及:

not type(1.01) == type(1)

但不等同于:

(not type(1.01)) == type(1)

Tags: theto函数falsetruetypenotsomething
3条回答

Python正在解析

not(type(1.01)) == type(1)

作为

^{pr2}$

(注意括号。)

显示operator precedence tablenot的优先级低于==。因此==运算符导致在应用not之前对{}进行求值。在


下面是另一种查看表达式计算方式的方法:

In [16]: type(1.01)
Out[16]: float

In [17]: type(1)
Out[17]: int

In [18]: float == int
Out[18]: False

In [19]: not float == int   # This is same as `not (float == int)`
Out[19]: True

In [20]: not (float) == int    
Out[20]: True

In [21]: not (type(1.01)) == int
Out[21]: True

In [22]: not (type(1.01)) == type(1)
Out[22]: True
>>> not type(1.01) == type(1)

psedocode中的含义

^{pr2}$

所以它会打印出True,因为float实际上不是int


在第二个例子中:

bool(type(1.01)) 
# True

运算符not产生相反的结果,因此由于True的对立面是False,所以它产生{}

not type(1.01) 
# False

在第三个例子中:

bool(type(1))
#True
False == type(1)
#False

由于True不等于False,它产生{}

实际上,您认为not是一个内置函数,并将not(..)用作调用函数。python not的fact是一个内置类型。所以add()不会改变结果。以下是python doc 2.7.5和3.2的一些参考:

http://docs.python.org/2/library/stdtypes.htmlhttp://docs.python.org/release/2.5.2/lib/boolean.html

他们都说: not的优先级低于非布尔运算符,因此nota==b被解释为not(a==b),a==not b是语法错误。 这正是你问题的答案。在

相关问题 更多 >