質問

質問 オブジェクトの平等のテストを実装するための優れたシンプルなソリューションを提供します。コンテキストの答えを繰り返します:

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__ これはスロットで動作するために?

役に立ちましたか?

解決

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

NB:thowに注意してください __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'

他のヒント

ジェフ、その多くのレコードを追跡する必要がある場合は、フライ級デザインパターンの使用を検討する必要があります。

見る: http://codesnipers.com/?q = Python-flywights

そのページは、追跡されたレコードの多くが同一の値を持っている状況について説明しています。その場合、フライ級パターンは非常に便利です。ただし、レコードに効果的に一意の値がある場合にも非常に便利です。 (その場合、値をnumpy配列/マトリックスなどに保存し、クラスにストレージをラップします)。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top