Proper syntax for adding methods to a class instance dynamically?
Geoff Gerrietts
geoff at gerrietts.net
Mon Apr 22 21:01:28 EDT 2002
Quoting Fernando Pérez (fperez528 at yahoo.com):
> I'd like to know what the proper way to do this is. I've been using the new
> module with new.instancemethod(), but the docstring for new isn't very
> confidence inducing:
>
> Is there a simpler, perhaps 'safer' way to achieve the same result? What I
> want is to have code which runs after an instance of a certain class has been
> created and which can add new methods to the class instance. I'd also like to
> know how to add them to the whole class. I have some solutions in store but I
> feel they're kind of kludgy.
I don't know much (read: anything) about instance methods, or how to
generate them, etc. So I can't help you much there. But, for adding a
method to a class, that's easy:
>>> class Spam:
... pass
...
>>> def eggs(self, stuff):
... print self, stuff
...
>>> Spam.eggs = eggs
>>> i = Spam()
>>> i.eggs("stuff")
<__main__.Spam instance at 0x81500e4> stuff
That'll work for a new-style class, too.
--G.
--
Geoff Gerrietts <geoff at gerrietts net> http://www.gerrietts.net/
"Now, now my good man, this is no time for making enemies."
--Voltaire, on his deathbed, when asked to renounce Satan
More information about the Python-list
mailing list