为什么{}}[]()| str | set |等>;在python2.x中n等于真?
我在尝试比较时注意到:为什么{}}[]()| str | set |等>;在python2.x中n等于真?,python,python-2.7,comparison,Python,Python 2.7,Comparison,我在尝试比较时注意到: if len(sys.argv) >= 2: pass 但我已经这么做了,而且仍然是真的(我花了一些时间找到了bug): 以下是更多的例子: >>> {} > 2 True >>> [] > 2 True >>> () > 2 True >>> set > 2 True >>> str > 2 True >>> enum
if len(sys.argv) >= 2:
pass
但我已经这么做了,而且仍然是真的(我花了一些时间找到了bug):
以下是更多的例子:
>>> {} > 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
>>>{}>2
符合事实的
>>> [] > 2
符合事实的
>>> () > 2
符合事实的
>>>设置>2
符合事实的
>>>str>2
符合事实的
>>>枚举>2
符合事实的
>>>_uuu内置\uuuuu>2
符合事实的
>>>课堂测试:
... 通过
...
>>>试验
>>>测试>2
符合事实的
在python3.x中,它会导致类型错误。您正在比较不同的类型。在Python2中,类型是按名称相对彼此排序的,数字类型总是排在其他类型之前 这是为了允许对包含不同类型数据的异构列表进行排序而引入的 Python3纠正了这一有点令人惊讶的行为,将类型(与数字或彼此)进行比较总是一个错误,除非自定义比较挂钩特别允许:
>>> {} > 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
>>>{}>3
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:无序类型:dict()>int()
>>>Foo类:
... 定义(自身、其他):
... 如果isinstance(其他,int):
... 返回真值
...
>>>Foo()>3
符合事实的
您正在比较不同的类型。在Python2中,类型是按名称相对彼此排序的,数字类型总是排在其他类型之前
这是为了允许对包含不同类型数据的异构列表进行排序而引入的
Python3纠正了这一有点令人惊讶的行为,将类型(与数字或彼此)进行比较总是一个错误,除非自定义比较挂钩特别允许:
>>> {} > 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
>>>{}>3
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:无序类型:dict()>int()
>>>Foo类:
... 定义(自身、其他):
... 如果isinstance(其他,int):
... 返回真值
...
>>>Foo()>3
符合事实的
非常感谢,现在我明白了!非常感谢,现在我明白了!