有人可以解释这个棘手的输出:
>>> 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)不会改变运算符优先级的原因。例如:
not(type(1.01)) == type(1)
与:
相同not(type(1.01) == type(1))
和
not type(1.01) == type(1)
但不一样:
(not type(1.01)) == type(1)
答案 0 :(得分:11)
Python正在解析
not(type(1.01)) == type(1)
as
not ((type(1.01)) == type(1))
(请注意括号。)
operator precedence table次展示not
的优先级低于==
。因此==
运算符会导致type(1.01) == type(1)
在应用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
答案 1 :(得分:4)
你不认为不是内置函数,而是使用not(..)作为函数调用。事实上,python不是内置的类型。所以add()不会改变结果。这些是python doc 2.7.5和3.2的一些参考:
http://docs.python.org/2/library/stdtypes.html http://docs.python.org/release/2.5.2/lib/boolean.html
他们都说: 没有比非布尔运算符更低的优先级,因此不是a == b被解释为不是(a == b),而a ==不是b是语法错误。 这正是你问题的答案。答案 2 :(得分:2)
>>> not type(1.01) == type(1)
表示psedocode
if 'float'is not a 'int':
then print True
所以它打印为True ,因为float实际上不是int
在第二个例子中:
bool(type(1.01))
# True
not
运算符生成相反的结果,因此True
的对面是False
,它会生成False
not type(1.01)
# False
在第三个例子中:
bool(type(1))
#True
False == type(1)
#False
由于True
不等于False
,因此会产生False