为什么{} | [] |()| str | set |等。 > n等于True在python2.x? [英] Why does {}|[]|()|str|set|etc. > n equals True in python2.x?

查看:124
本文介绍了为什么{} | [] |()| str | set |等。 > n等于True在python2.x?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I noticed this when trying to compare:

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

但我已经这样做了,仍然是True(让我一些时间找到错误。 ):

but I had done this and still was True (Took me some time to find the bug.):

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。

In python3.x it causes a TypeError.

推荐答案

您正在比较不同的类型。在Python 2中,类型通过名称相对于彼此排序,并且数字类型总是在所有其他类型之前排序。

You are comparing different types. In Python 2, types are ordered relative to one another by their name, and numeric types are always ordered before everything else.

引入它允许对包含不同类型数据的异构列表进行排序。

This was introduced to allow sorting of heterogeneous lists, containing different types of data.

Python 3纠正了这种有点令人惊讶的行为,比较类型(数字或彼此)总是一个错误,除非自定义比较钩子明确允许:

Python 3 rectifies this somewhat surprising behaviour, there comparing types (to numbers or to one another) is always an error unless specifically allowed by custom comparison hooks:

>>> {} > 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

这篇关于为什么{} | [] |()| str | set |等。 &gt; n等于True在python2.x?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆