Dynamically adding and removing methods
Ron Adam
rrr at ronadam.com
Sun Sep 25 10:52:56 EDT 2005
Steven D'Aprano wrote:
> Or you could put the method in the class and have all instances recognise
> it:
>
> py> C.eggs = new.instancemethod(eggs, None, C)
> py> C().eggs(3)
> eggs * 3
Why not just add it to the class directly? You just have to be sure
it's a class and not an instance of a class.
>>> def beacon(self, x):
... print "beacon + %s" % x
...
>>> C.beacon = beacon
>>> dir(A)
['__doc__', '__module__', 'beacon', 'ham', 'spam']
>>> A.beacon(3)
beacon + 3
>>> del beacon
>>> dir(A)
['__doc__', '__module__', 'beacon', 'ham', 'spam']
>>> A.beacon(3)
beacon + 3
>>> dir(C)
['__doc__', '__module__', 'beacon', 'ham', 'spam']
Cheers,
Ron
More information about the Python-list
mailing list