Ism*_* Vc 1 python comparison python-2.7
我在尝试比较时注意到了这一点:
if len(sys.argv) >= 2:
pass
Run Code Online (Sandbox Code Playgroud)
但我做到了这一点仍然是真的(花了我一些时间来找到这个bug.):
if sys.argv >= 2: # This is True!!!
pass
Run Code Online (Sandbox Code Playgroud)
以下是一些例子:
>>> {} > 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
Run Code Online (Sandbox Code Playgroud)
在python3.x中它会导致TypeError.
您正在比较不同的类型.在Python 2中,类型按名称相对于彼此排序,并且数字类型始终在其他所有类型之前排序.
引入它是为了允许对包含不同类型数据的异构列表进行排序.
Python 3纠正了这种有些令人惊讶的行为,除非自定义比较钩子特别允许,否则比较类型(数字或彼此)始终是错误:
>>> {} > 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
Run Code Online (Sandbox Code Playgroud)