Proper syntax for adding methods to a class instance dynamically?

Greg Ewing greg at cosc.canterbury.ac.nz
Tue Apr 23 01:47:26 EDT 2002


Fernando Pérez wrote:
> 
> Docstring:
>     Functions to create new objects used by the interpreter.
> 
>     You need to know a great deal about the interpreter to use this!
> 
> Is there a simpler, perhaps 'safer' way to achieve the same result?

Nothing simpler, and there isn't really anything "dangerous"
about new.instancemethod. If you're worried that the details
might change in a future version of Python (which is possible,
since the functions in the new module depend somewhat on the
internals) you could do this:

   def create_instance_method(inst, func):
     c = inst.__class__
     c.temp_method = func
     meth = inst.temp_method
     del c.temp_method
     return meth

   def f(self):
     print "Hi, I'm", self

   class C:
     pass

   i = C()
   i.new_method = create_instance_method(i, f)
   i.new_method()

> I'd also like to know how to add them to the whole class.

That's easy -- just assign a plain function to a class
attribute, e.g.

  C.some_method = f

-- 
Greg Ewing, Computer Science Dept, University of Canterbury,	  
Christchurch, New Zealand
To get my email address, please visit my web page:	  
http://www.cosc.canterbury.ac.nz/~greg



More information about the Python-list mailing list