adding methods at runtime

John Machin sjmachin at lexicon.net
Fri Jan 11 05:00:40 EST 2008


On Jan 11, 10:44 am, Marc 'BlackJack' Rintsch <bj_... at gmx.net> wrote:
> On Thu, 10 Jan 2008 14:55:18 -0800, zsl... at gmail.com wrote:
> > Can I access the class attributes from a method added at runtime? (My
> > experience says no.)
> > I experimented with the following code:
>
> > [Code snipped]
>
> > So it seems to me, if you add a method to an instance, the method will
> > not get "self" as parameter.
>
> You are not adding a method but a function.  Take a look at
> `types.MethodType()` to create a method from a function, instance, and
> class.
>

Just in case gentle readers are wondering where to find the docs for
types.MethodType, here's a hint:

>>> import types, new; types.MethodType is new.instancemethod
True
>>>





More information about the Python-list mailing list