Python list remove method: how's the implementation?
In java, I have my client class that have the "code" attr, and the equals method. Method equals receives another client and compares with itself's code attr.
In python, I just read that we have the __cmp__
method, to do the same as java method equals. Ok, I did that. I created my class client, with "code" attr and the method comp that verify if the code is the same.
class Client():
def __init__(self, code):
self.code = code
def __cmp__(self, obj):
return obj.code == self.code
def __repr__(self):
return str(self.code)
Then I put 3 Cl开发者_StackOverflow社区ient objects in a python's list:
bla = [Client(1), Client(2), Client(3)]
Then, when I try:
bla.remove(Client(3))
The amazing python removes the first element (the Client with code 1).
What I am doing wrong? I searched the implementation of list in python's Lib files, but is not easy to find.
Anyone can help?
http://docs.python.org/reference/datamodel.html#object.__cmp__
__cmp__(self, other)
Called by comparison operations if rich comparison (see above) is not defined. Should return a negative integer if self < other, zero if self == other, a positive integer if self > other.
Basically, you should change your implementation of __cmp__
to be...
def __cmp__(self, obj):
return cmp(obj.code, self.code)
The cmp()
builtin function of Python is specifically designed to return the values that __cmp__
is expected to return by comparing its two arguments.
There is also a different function in Python called __eq__
which only checks equality, for which your current implementation of __cmp__
would be better suited.
Sounds like you actually want __eq__
class Client():
def __init__(self, code):
self.code = code
def __eq__(self, obj):
return obj.code == self.code
# this is how you usually write cmp, Amber explained the problem
def __cmp__(self, other):
return cmp(self.code, other.code)
def __repr__(self):
return str(self.code)
Btw, what happens in your buggy example is that __cmp__
returns False as expected. But in Python False == 0
and returning 0 from __cmp__
means the compared elements are equal. So that is why it removes the first element!
精彩评论