假设重复A(2)
是一个错字,我认为你只需要定义__hash__
(参见docs http://docs.python.org/2/reference/datamodel.html#object.__hash__):
import numpy as np
from functools import total_ordering
@total_ordering
class A(object):
def __init__(self, a):
self.a = a
def __lt__(self, other):
return self.a < other.a
def __eq__(self, other):
return self.a == other.a
def __ne__(self, other):
return self.a != other.a
def __hash__(self):
return hash(self.a)
def __repr__(self):
return "A({})".format(self.a)
def __str__(self):
return repr(self)
produces
>>> map(A, range(3)+range(3))
[A(0), A(1), A(2), A(0), A(1), A(2)]
>>> set(map(A, range(3)+range(3)))
set([A(0), A(1), A(2)])
>>> np.unique(map(A, range(3)+range(3)))
array([A(0), A(1), A(2)], dtype=object)
我用过的地方total_ordering http://docs.python.org/2/library/functools.html#functools.total_ordering减少方法的扩散,正如您猜测的那样是可能的。 :^)
[发布后编辑以更正缺失的内容__ne__
.]