Почему 0 <() имеет значение True в Python?
Я случайно набрал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
оценивая, как если бы они были больше, чем любое число?
Обновить:
Виктор указал, что адреса памяти сравниваются по умолчанию:
>>> map(lambda _:(id(0),'<',id(_)),((),[],{}, set([])))
[(31185488L, '<', 30769224L), (31185488L, '<', 277144584L), (31185488L, '<', 279477880L), (31185488L, '<', 278789256L)]
Несмотря на кажущийся порядок,это неверно.
Мартейн Питерс указывает на то, что:Без явного оператора сравнения Python 2 сравнивает по Numbers и Type-names с числами, имеющими самый низкий приоритет.
Это не указывает на то, какие именно внутренние методы вызываются. Смотрите также это полезно, нонеокончательная SO тема:
В 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]