【发布时间】:2013-09-02 05:37:06
【问题描述】:
我无意中输入了time.clock<(),Python 2.7 解释器的响应是:True。以下代码举例说明了该行为:
>>> repr(time.clock)
'<built-in function clock>'
>>> time.clock<()
True
此外:
>>> import sys
>>> sys.maxint < ()
True
>>> map(lambda _:0<_,((),[],{}))
[True, True, True]
相比之下:
>>> 1<set(())
TypeError: can only compare to a set
问题:除了为什么之外,空的list、tuple 或dict 评估好像大于任何数字有实际意义或目的吗?
更新:
-
Viktor 指出默认情况下会比较内存地址:
>>> map(lambda _:(id(0),'<',id(_)),((),[],{}, set([])))[(31185488L, '<', 30769224L), (31185488L, '<', 277144584L), (31185488L, '<', 279477880L), (31185488L, '<', 278789256L)]
尽管看起来顺序,这是不正确的。
- Martijn Pieters 指出:
如果没有明确定义比较运算符,Python 2 会比较 数字和类型名称,数字的优先级最低。
这并不暗示正在调用的确切内部方法。另请参阅这很有帮助但inconclusive SO thread:
在 IPython 2.7.5 REPL 中
>>> type(type(()).__name__)
Out[15]: str
>>> type(()) < 10
Out[8]: False
>>> 10 < type(())
Out[11]: True
#as described
>>> type(()) < type(())
Out[9]: False
>>> type(()) == type(())
Out[10]: True
However:
>>> 'somestr' .__le__(10)
Out[20]: NotImplemented
>>> 'somestr' .__lt__(10)
Out[21]: NotImplemented
>>> int.__gt__
Out[25]: <method-wrapper '__gt__' of type object at 0x1E221000>
>>> int.__lt__
Out[26]: <method-wrapper '__lt__' of type object at 0x1E221000>
>>> int.__lt__(None)
Out[27]: NotImplemented
#.....type(...), dir(...), type, dir......
#An 'int' instance does not have an < operator defined
>>> 0 .__lt__
Out[28]: AttributeError: 'int' object has no attribute '__lt__'
#int is actually a subclass of bool
>>>int.__subclasses__()
Out: [bool]
#str as the fallback type for default comparisons
>>> type(''.__subclasshook__)
Out[72]: builtin_function_or_method
>>> dir(''.__subclasshook__)
Out[73]:
['__call__',
'__class__',
'__cmp__',
'__delattr__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__gt__',
'__hash__',
'__init__',
'__le__',
'__lt__',
'__module__',
'__name__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__self__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__']
#IPython is subclassing 'str'
>>> str.__subclasses__()
Out[84]: [IPython.utils.text.LSString]
【问题讨论】:
-
请注意,在 python3 中,所有这些比较都会引发
TypeError:>>> 0 < () Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unorderable types: int() < tuple() -
维克托的回答不正确。
-
@Bakuriu 我也觉得应该如此。谢谢你的安慰。
-
这是在 python3 中通过向后不兼容的更改修复的尴尬事情之一(并且有充分的理由)。如果您没有令人信服的理由继续使用 python2(例如,无法升级盒子,或缺少依赖项),我强烈建议您开始使用 python3(但确实阅读各种“新功能”)
标签: python collections comparison boolean logic