In Python2, it's valid:
#!/usr/bin/python
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
a = ListNode(0)
b = ListNode(1)
print(a < b)
Output: True
But same code in Python3, it will raise exception:
#!/usr/bin/python3
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
a = ListNode(0)
b = ListNode(1)
print(a < b)
Raise exception:
Traceback (most recent call last):
File "c.py", line 11, in <module>
print(a < b)
TypeError: '<' not supported between instances of 'ListNode' and 'ListNode'
Why it's different?
add:
I can add __lt__
method to ListNode
to avoid the exception: ListNode.__lt__ = lambda a, b: id(a) - id(b)
.
But why there's no need for Python2 to add the __lt__
method?
In Python 2, when you lack __lt__
(or the older deprecated __cmp__
), the default comparison rules kick in, which, in this case, eventually ends up comparing the memory addresses of the objects in question (before that, it's putting numbers before other stuff, and comparing everything else based on the string name of the class).
But this is almost never useful; if you haven't defined how to order instances of a class, arbitrarily ordering them by memory address (which changes each run) is silently misbehaving in 99% of code.
Python 3 fails loudly when that happens so people don't rely on sorting unsortable things by accident; if someone sorts [1, 'a', (), None]
or even just a list
of your instances with undefined ordering, raising an exception is just more helpful. If memory address ordering is really what's needed, you can always implement it like you did, but that's a vanishingly rare use case.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.