5

Can somebody explain this tricky output:

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

What happens there? And why this happens?

Answer: When I asked question I treated not as a function, but actually not isn't a function. That's why not(#something) doesn't change operator precedence. For example:

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

is the same as:

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

and:

not type(1.01) == type(1)

but not the same as:

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

3 回答 3

11

Python 正在解析

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

作为

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

(仔细注意括号。)

运算符优先级表显示的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
于 2013-11-13T11:23:03.773 回答
4

实际上,您认为 not 作为内置函数并使用 not(..) 作为调用函数。Python 的 Infact 不是内置类型。所以 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

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

于 2013-11-13T11:37:08.590 回答
2
>>> not type(1.01) == type(1)

means in psedocode

if 'float'is not a 'int':
      then print True

so it'd print True as a float is actually not a int


In the second example:

bool(type(1.01)) 
# True

The not operator produces the opposite result, Therefore since opposite of True is False, It produces False

not type(1.01) 
# False

In the third example:

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

Since True is not equal to False it produces False

于 2013-11-13T11:28:24.523 回答