Contains/equals

Christian Heimes lists at cheimes.de
Thu Aug 19 15:20:50 EDT 2010


Am 19.08.2010 20:53, schrieb Tim Chase:
> On 08/19/10 12:42, Steven D'Aprano wrote:
>> On Thu, 19 Aug 2010 11:00:03 -0400, Alex Hall wrote:
>>
>>>   def __eq__(self, obj):
>>>    if self.a==obj.a and self.b==obj.b: return True
>>>    return False
>>
>> That would be the same as:
>>
>>     def __eq__(self, obj):
>>       return self.a==obj.a and self.b==obj.b
> 
> Or, if you have lots of attributes and 2.5+
> 
>    def __eq__(self, other):
>      return all(
>        getattr(self, attr) == getattr(other, attr)
>        for attr in ['a', 'b', 'c', ...]
>        )
> 
> or even something like
> 
>    def __eq__(self, other):
>      return all(
>        getattr(self, attr) == getattr(other, attr)
>        for attr in dir(self)
>        if not attr.startswith("__") and not attr.endswith("__")
>        )
> 

or simpler if you don't take slots and class attributes into account.

    def __eq__(self, other):
        return self.__dict__ == other.__dict__

Christian




More information about the Python-list mailing list