В программе у меня происходит что-то вроде этого:
class MyClass:
def __init__(self, index, other_attribute)
self.index = index #is of type int
self.other_attribute = other_attribute
# I know this is being taken out of python 3,
# but I haven't converted it to using __eq__ etc.
def __cmp__(self, other):
if self.index < other.index:
return -1
if self.index == other.index:
return 0
if self.index > other.index:
return -1
вот проблема
#here are some objects
a = MyClass(1, something)
b = MyClass(1, something_else)
c = MyClass(2, something_more)
ary = [a,c]
if b not in ary:
ary.append(b)
Это не добавит b, потому что их индексы равны, но они по-прежнему разные экземпляры. Это b == a
верно, но b is a
неверно. Я хотел бы проверить членство по адресу, а не по эквивалентности. Есть ли способ заставить операторов in
и not in
использовать is
, а не ==
? Существуют ли другие операторы / алгоритмы, которые могли бы решить эту проблему?