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

前端 未结 7 1031
囚心锁ツ
囚心锁ツ 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:53

    For me this works perfectly using Python 2.5.2 on Win32. Using you class definition and the following test:

    f = Fooset([1,2,4])
    s = sets.Set((5,6,7))
    print f, f.foo
    f.foo = 'bar'
    print f, f.foo
    g = f | s
    print g, g.foo
    assert( (f | f).foo == 'bar')
    

    I get this output, which is what I expect:

    Fooset([1, 2, 4]) default
    Fooset([1, 2, 4]) bar
    Fooset([1, 2, 4, 5, 6, 7]) bar
    

提交回复
热议问题