开发者

In Python, None evaluates to less than zero? [duplicate]

This question already has answers here: 开发者_如何学编程 Is everything greater than None? (2 answers) Closed 9 years ago.

In Python, None evaluates to less than zero?

ActivePython 2.7.2.5 (ActiveState Software Inc.) based on
Python 2.7.2 (default, Jun 24 2011, 12:21:10) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> None < 0
True
>>> None == 0
False
>>> None > 0
False
>>>

Is this expected?

I would have guessed that None would either be equal to zero (through type coercion), or that all of these statements would return False.


See the manual:

Objects of different types, except different numeric types and different string types, never compare equal; such objects are ordered consistently but arbitrarily (so that sorting a heterogeneous array yields a consistent result).

and

CPython implementation detail: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.


From the docs:

CPython implementation detail: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.

NoneType compares as smaller than int since the comparison appears to be case-sensitive.

>>> type(0)
<type 'int'>
>>> type(None)
<type 'NoneType'>
>>> 'NoneType' < 'int'
True


It is intentional to make operations like sorting and dictionary comparison well defined.

[citing from the Language Reference]

The operators <, >, ==, >=, <=, and != compare the values of two objects. The objects need not have the same type. If both are numbers, they are converted to a common type. Otherwise, objects of different types always compare unequal, and are ordered consistently but arbitrary.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜