Is there an official way to add methods to an instance?
Peter Otten
__peter__ at web.de
Fri Apr 4 04:29:56 EDT 2008
Brian Vanderburg II wrote:
> I don't know if this is the correct place to send this question.
It is.
> 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.
[snip]
I think "Try hard to avoid __del__()" is as close to an official stance as
you can get ;)
Anyway, here is one more option to add too the zoo:
>>> class A(object):
... def __init__(self, f, x):
... self._f = f
... self.x = x
... @property
... def f(self):
... return self._f.__get__(self)
... def __del__(self):
... print "deleting"
...
>>> a = A(lambda s: s.x * 2, 2)
>>> b = A(lambda s: s.x * 3, 3)
>>> a.f()
4
>>> b.f()
9
>>> del a
deleting
>>> del b
deleting
Peter
More information about the Python-list
mailing list