Overriding methods per-object
castironpi at gmail.com
Sat Apr 18 04:33:05 CEST 2009
On Apr 17, 9:28 pm, Pavel Panchekha <PavPanche... at gmail.com> wrote:
> > The docs don't say you can do that:
> Thanks, hadn't noticed that.
> > Should you be able to?
> I'd say so. In my case, I need a class that can encapsulate any
> object, add a few methods to it, and spit something back that works
> just like the object, but also has those extra methods. I can't just
> add the methods, because it has to work on e.g. lists. So I'll have to
> end up defining all the possible methods on that class (and that's
> still not best because I can't use hasattr to test if, for example,
> addition is allowed on that object).
> On the other hand, I see how this severely restricts the possibly
> optimizations that can be made in the interpreter.
Can you dynamically subclass it:
def subclasser( obj ):
class newclass( obj.__class__ ):
FYI, the __class__ member is assignable, though I've personally never
done it in practice.
More information about the Python-list