new.instancemethod questions
schickb
schickb at gmail.com
Fri Jan 30 01:20:14 EST 2009
On Jan 29, 8:51 pm, Brian Allen Vanderburg II
<BrianVanderbu... at aim.com> wrote:
> You can also create a bound method and manually bind it to the
> instance. This is easier
>
> import types
> a.f2 = types.MethodType(f1, a)
>
> a.f2() # prints object a
Ah thanks, that is what I was looking for. I missed that because
following types.MethodType in the docs is:
types.UnboundMethodType
An alternate name for MethodType
Which made me think it was a type for UnboundMethods (aka functions).
This:
>>> help(types.UnboundMethodType)
clears it up for me, but the docs are rather confusing.
> These may work for most uses, but both have a problem that happens if
> you need to make a copy of the instance. When you copy it, the copies
> 'f1' will still call the function but using the old object
>
> a.f1() # prints object a
> b = copy.copy(a)
> b.f1() # still prints a
>
Ugh, that is a problem. I guess that means pickling won't work
either....
Nope, "TypeError: can't pickle instancemethod objects". So does these
mean there is no way to create a method on an instance at runtime that
behaves just like a method that originated from the instance's class?
-Brad
More information about the Python-list
mailing list