On 10月30日, 下午4时44分, Bruno Desthuilliers <bruno. 42.desthuilli...@websiteburo.invalid> wrote: > metal a écrit : > > > The actual situation is I'm coding with a immuable set-like datatype > > XSet which supports XSet(['al']) & XSet(['ah'] = XSet(['ax'] > > I assume it was '==', not '=' > > > if I > > declare ax is consists of al and ah > > > "That" means I can't explian it very well 'cause my english... > > > Now I try to make some mess like this...I know it's not good to wrap > > all methods...I just try to make code looks good > > > class MyMeta(type): > > def __init__(cls, name, bases, namespace): > > type.__init__(cls, name, bases, namespace) # needed? > > cls.wrap_methods() > > def methods(cls): > > return [k for k, v in cls.__dict__.items() if callable(v)] > > All callables are not functions or methods... The inspect module might > help you here. > > > def wrap_methods(cls): > > for k in cls.methods(): > > f = cls.__dict__[k] > > Just for the record, you wouldn't have to do this lookup if .methods > returned the actual objects instead of their names) if callable(v)). > > > def g(self, *v, **k): > > rv = f(self, *v, **k) > > if rv.__class__ is cls: > > rv = self.__class__() > > rv.__dict__.update(self.__dict__) > > return rv > > setattr(cls, k, g) > > If you do have control over the whole class hierarchy, just write the > base class so the alternate constructors return instances of the > appropriate class. Else, manually wrapping the relevant methods would be > a better solution IMHO. I'm not for premature optimization, but remember > that method lookup and function call are two costly operations in > Python, so better not adding too much overhead.
All code are just POCs. == or = doesn't matter :) Sure I know .methods() can return actual objects if ONLY iteration, but how to overwrite it? type(self) in new-style class looks a little better, thanks for the idea -- http://mail.python.org/mailman/listinfo/python-list