【问题标题】:Is there any way how to make set operators work with sets, in which objects are stored?有什么方法可以使集合运算符与存储对象的集合一起工作?
【发布时间】:2019-04-27 13:02:15
【问题描述】:

我正在尝试找到一种方法来比较集合中的对象以使 & 运算符在它们上正常工作。

我试图找到设置函数intersect() 的源代码,但毫无希望。我试图重载等号运算符,但是当我将__eq__() 函数添加到类定义中时,Person 对象变得不可散列。

class Person:
    def __init__(self, dictionary):
        self.dictionary = dictionary

def foo1():
    first_set.add(Person({"age" : 20}))

def foo2():
    second_set.add(Person({"age" : 20}))

first_set = set()
second_set = set()

foo1()
foo2()

print(first_set)
print(second_set)
print(first_set & second_set)  # I'd like to get non-empty intersection here

我认为它可以通过__eq__() 重载以某种方式工作,但这是不可能的。

【问题讨论】:

标签: python object set


【解决方案1】:

要使您的类集合像这样安全,您需要同时覆盖 __eq____hash__ - 请参阅 https://hynek.me/articles/hashes-and-equality/Recommended way to implement __eq__ and __hash__

【讨论】:

  • 当然,字典(可变)不能安全地散列。
  • 没错 - 你需要某种frozendict
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-05
  • 2018-08-07
  • 1970-01-01
  • 1970-01-01
  • 2017-09-18
  • 1970-01-01
相关资源
最近更新 更多