8

另一个问题为实现对象相等性测试提供了一个很好、简单的解决方案。我将重复上下文的答案:

class CommonEqualityMixin(object):

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

    def __ne__(self, other):
        return not self.__eq__(other)

class Foo(CommonEqualityMixin):

    def __init__(self, item):
        self.item = item

我想为使用__slots__. 我知道基类和子类都必须使用插槽,但是您将如何定义__eq__它以使用插槽?

4

2 回答 2

9
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)

使用示例:

class Foo(CommonEqualityMixin):
    __slots__ = ('a', )
    def __init__(self, a):
        self.a = a

Foo(1) == Foo(2)
# False
Foo(1) == Foo(1)
# True

注意:请注意__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)
# True

print FooBar(1, 1).__slots__
# 'z'
于 2010-12-23T22:22:54.743 回答
1

Jeff,如果您需要跟踪这么多记录,您应该考虑使用享元设计模式。

请参阅:http ://codesnipers.com/?q=python-flyweights

该页面描述了许多跟踪记录具有相同值的情况。在这种情况下,享元模式非常有用。但是,当记录具有有效的唯一值时,它也非常有用。(在这种情况下,您将值存储在 numpy 数组/矩阵等中,并将存储包装在一个类中)。

于 2011-09-19T23:39:22.740 回答