Contains/equals

Alex Hall mehgcap at gmail.com
Thu Aug 19 17:00:03 CEST 2010


On 8/19/10, Peter Otten <__peter__ at web.de> wrote:
> Karsten Wutzke wrote:
>
>> I have an object which has a list of other complex objects. How do I
>> best achieve a complex "contains" comparison based on the object's
>> class? In Java terms, I'm looking for an equivalent to equals(Object)
>> in Python. Does a similar thing exist? Directions appreciated.
>
> I can't infer from your question whether you already know about
> __contains__(). So there:
>
>>>> class Cornucopia:
> ...     def __contains__(self, other):
> ...             return True
> ...
>>>> c = Cornucopia()
>>>> 42 in c
> True
>>>> "cherry pie" in c
> True
>>>> c in c
> True
You may also want to use the double equals operator; in Java, one
thing I wish I could do is
String s="abc";
String t="def";
if(s==t)...
In Python, as I understand it, you can define this behavior.

class c(object):
 def __init__(self, a=1, b=2):
  self.a=a; self.b=b

 def __eq__(self, obj):
  if self.a==obj.a and self.b==obj.b: return True
  return False


You can now say:
obj1=c()
obj2=c()
print(obj1==obj2) #prints True
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap



More information about the Python-list mailing list