为什么重载相等的运算符会使我的对象不可删除?

时间:2017-12-22 09:54:53

标签: python operator-overloading

我有这个对象:

class MyObject:

    def __init__(self, name: str, collections: list = None):
        self.name = name
        self.collections = collections

我有另一个包含一组MyObject

的类
class MyObjectHolder:

    def __init__(self):
        self.my_objects = set()

    def AddMyObject(self, my_object: MyObject):
        self.my_objects.add(my_object)

到目前为止这个工作正常,但由于其他一些原因,我想重载MyObject的等于运算符:

class MyObject:

    def __init__(self, name: str, collections: list = None):
        self.name = name
        self.collections = collections

    def __eq__(self, other):
        if isinstance(other, MyObject):
            return self.name == other.name
        else:
            return NotImplemented

但是,当我在重载等于运算符后调用方法AddMyObject时,我收到以下错误:

TypeError: unhashable type: 'MyObject'

为什么会这样?

0 个答案:

没有答案