Is there an official way to add methods to an instance?

Roger Miller roger.miller at nova-sol.com
Thu Apr 3 21:43:30 EDT 2008


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

Output:
42
Deleting



More information about the Python-list mailing list