class x:
def __init__(self,name):
self.name=name
def __str__(self):
return self.name
def __cmp__(self,other):
print("cmp method called with self="+str(self)+",other="+str(other))
return self.name==other.name
# return False
instance1=x("hello")
instance2=x("there")
print(instance1==instance2)
print(instance1.name==instance2.name)
The output here is:
cmp method called with self=hello,other=there
True
False
Which is not what I expected: I'm trying to say 'two instances are equal if the name fields are equal'.
If I simply return False
from the __cmp__
function, this reports as True
as well!!
If I return -1
, then I get False
- but since I'm trying to compare strings, this doesn't feel right.
What am I doing wrong here?
In Python 2, __cmp__(self, other) implemented comparison between two objects, returning a negative value if self < other , positive if self > other , and zero if they were equal.
cmp() does not work in python 3.
from python wiki: In Py3. 0, the cmp parameter was removed entirely (as part of a larger effort to simplify and unify the language, eliminating the conflict between rich comparisons and the __cmp__ methods). The latter is very verbose and the same purpose is achieved in the former with just one line.
The cmp() is part of the python standard library which compares two integers. The result of comparison is -1 if the first integer is smaller than second and 1 if the first integer is greater than the second. If both are equal the result of cmp() is zero.
__cmp__(x,y)
should return a negative number (e.g. -1) if x < y
, a positive number (e.g. 1) if x > y
and 0 if x == y
. You should never return a boolean with it.
What you're overloading is __eq__(x, y)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With