2012-01-22 26 views
17
Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on win32 
Type "help", "copyright", "credits" or "license" for more information. 
>>> None > 0 
False 
>>> None == 0 
False 
>>> None < 0 
True 
  • 是使用内置类型(整数在这种情况下)明确定义的算术运算符比较None
  • 语言规范的前两个和第三个比较部分之间的区别(Python的规范 - 你必须在开玩笑:))还是CPython的实现细节?
+4

'=='和'!='通常是安全的,但你应该使用'是None'和'不None'为单身如'None'按[PEP-8](http://www.python.org/dev/peps/pep-0008/) – ThiefMaster

+2

@ThiefMaster问题的关键是*安全*在这里的含义。我很清楚应该使用'is'来比较'None',但问题是特定的,并且不会询问应该使用哪个运算符。 –

+0

http://bugs.python.org/issue1673405 – wim

回答

17

您真正可以使用None的唯一有意义的比较是if obj is None:(或if obj is not None:)。

不同类型之间的比较已从Python 3中删除,原因很充分 - 它们是错误的常见来源,并导致混淆。例如

>>> "3" < 4 
False 

在Python 3,你比较不同类型的值时,像strint或任何与None得到TypeError

>>> None < 0 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: unorderable types: NoneType() < int() 

(我的意思是在试图确定哪两个数值越大/小平等比较正常意义上的“比较” - 它总是返回False如果两个对象是不同类型的。)

我没有找到的文档此的引用,但在Learning Python, 4th edition,马克·鲁茨204页上写道:

[...] Comparisons of differently typed objects (e.g., a string and a list) work — the language defines a fixed ordering among different types, which is deterministic, if not aesthetically pleasing. That is, the ordering is based on the names of the types involved: all integers are less than all strings, for example, because "int" is less than "str" .

+0

文档中是否有关于此的任何信息? –

+1

为什么'None <0'是真的是什么原因? – wim

+4

@wim:'None'是Python 2中的“最低类型”,所以'None'总是低于任何'int',它总是低于任何'str'等。 –

4

一些有趣的报价从http://bytes.com/topic/python/answers/801701-why-none-0-a

In early Python, the decision was made that the comparison of any two objects was legal and would return a consistent result. So objects of different types will compare according to an ordering on their types (an implementation dependent, unspecified, but consistent ordering), and objects of the same type will be compared according to rules that make sense for that type.

Other implementations have the right to compare an integer and None differently, but on a specific implementation, the result will not change.

Python 3 will raise an exception on such comparisons.

The problem is the typical one; Python did not originally have a Boolean type, and the retrofit resulted in weird semantics. C has the same issue.

+0

这真的很恶心。尽可能避免Python 3的另一个原因。所以你现在不能排序异类对象的列表...... >>>> sorted([2,1.5,2.5]) [1.5,2,2。5] >>>排序([2,1.5,2.5,'bla','2','2.5',None]) 回溯(最近呼叫最后): 文件“”,第1行,在 TypeError:无法定义的类型:str()

+6

我会争辩说,作为_prefer_ python 3的理由......从'sorted([2,1.5,2.5,'bla','2','2.5',None])''的预期结果是什么? – moveaway00

相关问题