[Tutor] Dynamically changing a class
Kent Johnson
kent37 at tds.net
Wed Sep 5 13:22:23 CEST 2007
Ricardo Aráoz wrote:
> Yep. And once you've got it pls explain it too me, too lazy today to
> pick the manual. :)
I included a link to my explanation previously. I'm too lazy to try to
do better.
> Any easier way?
Easier how? I don't know what could be easier to implement than a single
function call. What did you have in mind? These are all equivalent, take
your pick:
myObj.mfunc = newfunc.__get__(myObj, MyClass)
myObj.mfunc = types.MethodType(newfunc, myObj, MyClass)
myObj.mfunc = new.instancemethod(newfunc, myObj, MyClass)
For my own interest I looked into how these are actually implemented
with an eye to which one might be preferred.
new.instancemethod has the advantage of being documented in the library
reference but the source says it is deprecated and it is a synonym for
types.MethodType (in new.py).
types.MethodType is defined in types.py as
MethodType = type(_x._m)
where _x is a class and _m is a method; i.e. types.MethodType is
literally 'the type of a bound method'. It is fairly explicit at the
point of use - 'give me a method'.
newfunc.__get__ is defined by func_descr_get() in Objects/funcobject.c.
It delegates to PyMethod_New() so it is essentially calling MethodType.
It's a bit obscure at the point of use.
So I guess I prefer MethodType(newfunc, myObj, MyClass)
Kent
More information about the Tutor
mailing list