创建一组 class 个包含该集合作为属性的对象?

Create a set of class objects which contain that very set as an attribute?

class Something:
    def __init__(self,x,y):
        self.x = x
        self.y = y
        self.z = set()

    def __hash__(self):
        return hash((self.x, self.y, self.z))

    def __eq__(self,other):
        if not isinstance(other, Something):
            return NotImplemented
        return self.x == other.x and self.y == other.y

以上是class的定义。主内:

blah = []

for i in range(5):
    blah.append(Something(i,i+1))

blah[0].z.add(blah[1])

为此,我收到 TypeError: unhashable type: 'set' 错误。我在这里找到的一个解决方案是使 z 成为 frozenset() 但这给出了 AttributeError: 'frozenset' object has no attribute 'add'.

有什么建议吗?

您应该从 __hash__ 方法中省略 self.z

由于您的 __eq__ 方法忽略了 self.z,因此 __hash__ 无论如何都要考虑它是不正确的。它解决了 self.z 是不可散列(和可变)类型的问题。