Skip to main content
 首页 » 编程设计

python之为什么 {}|[]|()|str|set|etc. > n 在 python2.x 中等于 True

2025年05月04日18飞鱼

我在尝试比较时注意到了这一点:

if len(sys.argv) >= 2: 
    pass 

但我已经这样做了并且仍然是正确的(我花了一些时间来找到错误。):

if sys.argv >= 2: # This is True!!! 
    pass 

这里还有一些例子:

>>> {} > 2 
True 
>>> [] > 2 
True 
>>> () > 2 
True 
>>> set > 2 
True 
>>> str > 2 
True 
>>> enumerate > 2 
True 
>>> __builtins__ > 2 
True 
>>> class test: 
...     pass 
...  
>>> test 
<class __main__.test at 0xb751417c> 
>>> test > 2 
True 

在 python3.x 中它会导致 TypeError。

请您参考如下方法:

您正在比较不同的类型。在 Python 2 中,类型按它们的名称相对于彼此排序,而数字类型总是排序在其他一切之前。

这是为了允许对包含不同类型数据的异构列表进行排序。

Python 3 纠正了这种有点令人惊讶的行为,除非自定义比较 Hook 特别允许,否则比较类型(与数字或彼此)总是错误的:

>>> {} > 3 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
TypeError: unorderable types: dict() > int() 
>>> class Foo: 
...     def __gt__(self, other): 
...         if isinstance(other, int): 
...             return True 
...  
>>> Foo() > 3 
True