I\'m implementing an object that is almost identical to a set, but requires an extra instance variable, so I am subclassing the built-in set object. What is the best way to
set1 | set2
is an operation that won't modify either existing set
, but return a new set
instead. The new set
is created and returned. There is no way to make it automatically copy arbritary attributes from one or both of the set
s to the newly created set
, without customizing the |
operator yourself by defining the __or__ method.
class MySet(set):
def __init__(self, *args, **kwds):
super(MySet, self).__init__(*args, **kwds)
self.foo = 'nothing'
def __or__(self, other):
result = super(MySet, self).__or__(other)
result.foo = self.foo + "|" + other.foo
return result
r = MySet('abc')
r.foo = 'bar'
s = MySet('cde')
s.foo = 'baz'
t = r | s
print r, s, t
print r.foo, s.foo, t.foo
Prints:
MySet(['a', 'c', 'b']) MySet(['c', 'e', 'd']) MySet(['a', 'c', 'b', 'e', 'd'])
bar baz bar|baz