Unexpected behaviour from the 'in' operator
sik0fewl
xxdigitalhellxx at hotmail.com
Mon Feb 24 10:06:15 EST 2003
Blair Hall wrote:
> I have just noticed that the 'in' operator for lists appears to
> use the __eq__ method of a class. This does not
> provide the behaviour I expected when implementing
> an ad hoc numeric class type.
>
> Here is some code:
>
> class A(object):
> def __init__(self,x):
> self.x = x
>
> def __eq__(self,other):
> print 'eq'
> return self.x == other
> #=============================
> if(__name__ == '__main__'):
> print
> x = A(1)
> y = A(1)
> lst = [x]
> print y in lst # prints 1
>
> The 'y in lst' expression evaluates to true here, because
> both x and y are equal to the same value. However,
> x and y are not the same object! It seems to me that
> the comparison should use something like the id() function
> instead of __eq__.
I don't know. It works the way I would've expected it to work. Because,
like you said, x == y and x is in list, therefore y is in list.
--
Ryan
More information about the Python-list
mailing list