在Python中,没有一个计算结果小于零?

2024-05-13 18:49:40 发布

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

在Python中,None的计算结果小于零?

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
>>>

这是预期的吗?

我猜None要么等于零(通过类型强制),要么所有这些语句都将返回False


Tags: nonefalsedefaultonbitsoftwarewinjun
3条回答

来自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.

NoneTypeint小,因为比较似乎区分大小写。

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

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).

以及

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.

它旨在使排序和字典比较等操作得到很好的定义。

[引自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.

相关问题 更多 >