Dynamically adding methods to a class...
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Wed Jul 30 01:09:01 EDT 2008
En Tue, 29 Jul 2008 01:17:13 -0300, Piyush Anonymous
<piyush.subscription at gmail.com> escribi�:
> 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:
py> o = MyObject("hello")
py> MyObject.custom_do_this = custom_do_this
py> o.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
More information about the Python-list
mailing list