16

ユーザー定義オブジェクトを比較する必要がある Python (3.2) でプロジェクトを行っています。compareTo()以下の例のように、クラスの自然な順序付けを指定するクラスでメソッドを定義する Java での OOP に慣れています。

public class Foo {
    int a, b;

    public Foo(int aa, int bb) {
        a = aa;
        b = bb;
    }

    public int compareTo(Foo that) {
        // return a negative number if this < that
        // return 0 if this == that
        // return a positive number if this > that

        if (this.a == that.a) return this.b - that.b;
        else return this.a - that.a;
    }
}

私はPythonのクラス/オブジェクトにかなり慣れていないので、クラスの自然な順序を定義する「pythonic」の方法は何ですか?

4

2 に答える 2

20

特別なメソッドなどを実装して、カスタム タイプのデフォルト オペレータを実装でき__lt__ます__gt__。詳細については、言語リファレンスを参照してください。

例えば:

class Foo:
    def __init__ (self, a, b):
        self.a = a
        self.b = b

    def __lt__ (self, other):
        if self.a == other.a:
            return self.b < other.b
        return self.a < other.b

    def __gt__ (self, other):
        return other.__lt__(self)

    def __eq__ (self, other):
        return self.a == other.b and self.b == other.b

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

または、コメントで stranac が言ったように、total_orderingデコレータを使用して入力を節約できます。

@functools.total_ordering
class Foo:
    def __init__ (self, a, b):
        self.a = a
        self.b = b

    def __lt__ (self, other):
        if self.a == other.a:
            return self.b < other.b
        return self.a < other.b

    def __eq__ (self, other):
        return self.a == other.b and self.b == other.b
于 2012-06-26T21:05:19.227 に答える
6

Python にも同様の機能があります: __cmp__().

あなたが Python 3 について質問していることがわかり ます

cmp() 関数はなくなったものとして扱い、__cmp__() 特殊メソッドは
はサポートされなくなりました。ソートには __lt__() を使用し、__hash__() では __eq__() を使用し、
必要に応じて他の豊富な比較。(本当に cmp() 機能が必要な場合は、
式 (a > b) - (a < b) を cmp(a, b) と同等のものとして使用できます)。

だから、いつでも次のようなことができるようです

def compareTo(self, that):
    return ((self > that) - (self < that))

また

@classmethod
def compare(cls, a, b):
    return ((a > b) - (a < b))

とを実装__gt__()した後__lt__()

次に、次のように使用します。

f1 = Foo(1,1)
f2 = Foo(2,2)

f1.compareTo(f2)
Foo.compare(f1,f2)

これにより、同等の機能が得られます。

于 2012-06-26T21:04:54.033 に答える