简体   繁体   English

设置实例之间的加法、减法、并集

[英]Set addition, subtraction, union between instances

What method(s) do I need to define in my class to be able to add together the following:我需要在我的类中定义什么方法才能将以下内容相加:

combined_set = set('a') | MyInstance
# want to get set(['a', MyInstance]) // instance is hashable
TypeError: unsupported operand type(s) for |: 'set' and 'MyInstance'

Unions, intersections, differences and symmetric differences of sets using the overloaded operators |使用重载运算符的集合的并、交、差和对称差| , & , - and ^ have to be done on two sets , not a set and a single element. , & , -^必须在两个集合上完成,而不是一个集合和一个元素。 But you can write {MyInstance} instead of MyInstance to have a set containing that single element.但是您可以编写{MyInstance}而不是MyInstance来拥有一个包含该单个元素的集合。

>>> the_set = {'a'}
>>> element = 'b'
>>> the_set | {element}
{'a', 'b'}
>>> the_set & {element}
set()
>>> the_set - {element}
{'a'}
>>> the_set ^ {element}
{'a', 'b'}

As HeapOverflow points out, if you use the union , intersection , difference or symmetric_difference methods instead of the overloaded operators, the argument only needs to be an iterable, not necessarily a set;正如 HeapOverflow 指出的那样,如果您使用unionintersectiondifferencesymmetric_difference方法而不是重载运算符,则参数只需要是可迭代的,不一定是集合; but that doesn't help in your case.但这对你的情况没有帮助。

You could do it one of these ways:您可以通过以下方式之一进行操作:

combined_set = set(('a', MyInstance))

combined_set = set('a') | { MyInstance }

combined_set = set('a')
combined_set.add(MyInstance)

You can define a你可以定义一个

__ior__(self, value)

for your class.为你的班级。

where value can be booth a set or another instance of your class.其中 value 可以是您的班级的集合或另一个实例。

But of course your class need to inherit from set.但是当然你的类需要从 set 继承。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM