By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,706 Members | 1,257 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,706 IT Pros & Developers. It's quick & easy.

Re: Dynamically adding methods to a class...

P: n/a
En Tue, 29 Jul 2008 01:17:13 -0300, Piyush Anonymous
<pi*****************@gmail.comescribi�:
class MyObject:
def __init__(self, name):
self.name = name

def do_this_default(self):
print "default do_this implementation for %s" % self.name

def custom_do_this(): #method to be added
print "custom do_this implementation for %s" % self.name
You forget the self argument (this explains the error you got).
def funcToMethod(func,clas,method_name=None):
"""Adds func to class so it is an accessible method; use method_name
to
specify the name to be used for calling the method.
The new method is accessible to any instance immediately."""
import new
method = new.instancemethod(func,None,clas)
print method
if not method_name: method_name=func.__name__
clas.__dict__[method_name]=func
It's a lot easier than that; just add the *function* object to the class
namespace:
setattr(clas, method_name, func)
If you know the name when you write the code, just set the attribute:

pyo = MyObject("hello")
pyMyObject.custom_do_this = custom_do_this
pyo.custom_do_this()
custom do_this implementation for hello

new.instancemethod is useful to add specific methods to individual
instances, but it's not used to add methods globally to the class.
Error I am getting;
TypeError: custom_do_this() takes no arguments (1 given)
Add the self argument and you're done.
Why am I getting it?

Also how can I do this in new style class (inherited from 'object')?
It's the same thing, no difference.

--
Gabriel Genellina

Jul 30 '08 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.