What is the correct (or best) way to subclass the Python set class, adding a new instance variable?

前端 未结 7 987
囚心锁ツ
囚心锁ツ 2021-01-01 20:45

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

7条回答
  •  春和景丽
    2021-01-01 20:54

    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 sets 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
    

提交回复
热议问题