简体   繁体   中英

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.

>>> 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; 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.

But of course your class need to inherit from set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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