dyn added methods dont know self?

Moshe Zadka moshez at math.huji.ac.il
Wed Feb 2 18:56:03 EST 2000


On Wed, 2 Feb 2000, Andrew Csillag wrote:

> > I want to add a method dynamically to an instance, how can I do this? I tried
> > with exec '...' in self.__dict__, but this method doesn't know the instance
> > reference 'self', so it would complain that it is called without an argument.
> > Is there any other method to add a method dynamically?
> 
> You can't add a method directly to an instance unless you write a little
> wrapper object to wrap self into it, i.e.

A better way would be

def add_method(instance, method, name):
	class new_class(instance.__class__):
		pass
	new_class.__dict__[name] = method
	instance.__class__ = new_class

What you're doing here is dynamically changing the class of the instance
to a subclass which has the method. Ain't it cool?

but-doing-that-probably-proves-the-design-was-flawed-ly y'rs, Z.
--
Moshe Zadka <mzadka at geocities.com>. 
INTERNET: Learn what you know.
Share what you don't.





More information about the Python-list mailing list