import operator
class CommonEqualityMixin(object):
__slots__ = ()
def __eq__(self, other):
if isinstance(other, self.__class__):
if self.__slots__ == other.__slots__:
attr_getters = [operator.attrgetter(attr) for attr in self.__slots__]
return all(getter(self) == getter(other) for getter in attr_getters)
return False
def __ne__(self, other):
return not self.__eq__(other)
Usage example:
class Foo(CommonEqualityMixin):
__slots__ = ('a', )
def __init__(self, a):
self.a = a
Foo(1) == Foo(2)
Foo(1) == Foo(1)
N.B: , __slots__ , __dict__, , , , FooBar, Foo,
:
class FooBar(Foo):
__slots__ = ('z')
def __init__(self, a, z):
self.z = z
super(FooBar, self).__init__(a)
FooBar(1, 1) == FooBar(2, 1)
print FooBar(1, 1).__slots__