Is there an official way to add methods to an instance?
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Thu Apr 3 22:08:46 EDT 2008
En Thu, 03 Apr 2008 22:43:30 -0300, Roger Miller
<roger.miller at nova-sol.com> escribió:
> On Apr 3, 2:57 pm, Brian Vanderburg II <BrianVanderbu... at aim.com>
> wrote:
>>
>> I've checked out some ways to get this to work. I want to be able to
>> add a new function to an instance of an object. I've tested two
>> different methods that cause problems with 'deleting'/garbage collection
>> (__del__ may never get called), but implemented one sort of hackishly
>> maybe that works find. I'm wondering if there is more of an official way
>> than mine.
>>
>
> Maybe I'm missing something, but the boring old straightforward
> approach works for me:
>
> class A:
> def __del__(self):
> print "Deleting"
>
> def f(x):
> print x
>
> a = A()
> a.f = f
> a.f(42)
> del a
This doesn't create an instance method. You can't access `a` (as `self`)
from inside f.
--
Gabriel Genellina
More information about the Python-list
mailing list