gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:12:36 25 4
gpt4 key购买 nike

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

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

关于python - 为什么 {}|[]|()|str|set|etc. > n 在 python2.x 中等于 True?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19743622/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com