有人可以解释这个棘手的输出:
>>> not(type(1.01)) == type(1) # Why does the expression evaluates to True!?
True
>>> not(type(1.01))
False
>>> False == type(1)
False
Run Code Online (Sandbox Code Playgroud)
那里发生了什么?为什么会这样?
答:
当我问问题我被not视为一个功能,但实际上not不是一个功能.这就是为什么不(#something)不会改变运算符优先级的原因.例如:
not(type(1.01)) == type(1)
Run Code Online (Sandbox Code Playgroud)
是相同的:
not(type(1.01) == type(1))
Run Code Online (Sandbox Code Playgroud)
和:
not type(1.01) == type(1)
但不一样:
(not type(1.01)) == type(1)
Run Code Online (Sandbox Code Playgroud)
unu*_*tbu 11
Python正在解析
not(type(1.01)) == type(1)
Run Code Online (Sandbox Code Playgroud)
如
not ((type(1.01)) == type(1))
Run Code Online (Sandbox Code Playgroud)
(仔细注意括号.)
该运算符优先级表显示了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
Run Code Online (Sandbox Code Playgroud)
小智 4
实际上,您将 not 视为内置函数并使用 not(..) 作为调用函数。事实上对于 python 来说不是内置类型。所以add()不会改变结果。这些是 python 文档 2.7.5 和 3.2 的一些参考:
http://docs.python.org/2/library/stdtypes.html http://docs.python.org/release/2.5.2/lib/boolean.html
他们都说: not 的优先级低于非布尔运算符,因此 not a == b 被解释为 not (a == b),并且 a == not b 是语法错误。这正是你问题的答案。