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?