What is the correct (or best) way to subclass the Python set class, adding a new instance variable? -
I am implementing an object that is almost identical to a set, but requires an additional frequency variable, so I am subclassing the underlying set object
Using the old set module, the following code works perfectly:
What is the best way to ensure that this variable Value is copied? Import set square Fooset (sets.Set): def __init __ (auto, S = []): sets.Set .__ init __ (self, if) isinstance (s, Fooset): self.foo = s .foo rest: self.foo = 'default' f = Fooset ([1,2,4]) f.foo = 'bar' says ((f | f) .foo == 'bar') But this does not work by using the built-in set module.
The only solution I can see is to override each method that returns the copied object ... in which case I do not bother as well as subclassing the set object, certainly not so Is there a standard way to do it?
(To clarify, the following code works not (claim fails):
square Fooset (set): def __init __ (self, s = []): set .__ init __ (self, if) isinstance (s, fooset): self.foo = s.foo rest: self.foo = 'default' f = fooset ([ 1,2,4]) f.foo = 'Bar' says ((f | f) .foo == 'bar') )
My favorite way of wrapping methods underlying the compilation:
class Fuset (set): Def __init __ (self, s = (), foo = none): super (fooset, self) .__ init __ (S) if foo has any other hasattr (s, 'foo'): foo = s.foo itself Foo = foo @classmethod DEF_wrap_methods (CLS, name): def wrap_method_closure (name): def inner (auto, * args): result = getattr (super (CLS, self), name) (* args) ifinstance (result, Set) and not name for hat name (set), (), (result, 'foo'): result = cls (result, foo = self.foo) return result inner.fn_name = name setattr (cls, name, internal ) name: wrap_method_closure (name) Fooset._wrap_methods ([ '__ror__', 'difference_update', '__isub__', 'symmetric_difference', '__rsub__', '__and__', '__rand__', 'crossroads',' difference ',' __iand__ ',' Union ',' __ixor__ ',' symmetric_difference_update ',' __or__ ',' duplicate ',' __rxor__ ',' intersection_update ',' __xor__ ',' __ior_ _ ',' __sub__ ',]) Essentially you are doing the same thing in your answer, but it is also easy to put in meta-tapping with little space , If you want to do the same with lists and documents.
Comments
Post a Comment