If a class Child inherits from Parent, how to implement Child.some_method if Parent.some_method() returns Parent instance ?
bruno.42.desthuilliers at websiteburo.invalid
Fri Oct 30 09:44:20 CET 2009
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?
> 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__()
> 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.
More information about the Python-list