<pi*****************@gmail.comescribi�:
class MyObject:You forget the self argument (this explains the error you got).
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
def funcToMethod(func,clas,method_name=None):It's a lot easier than that; just add the *function* object to the class
"""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
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;Add the self argument and you're done.
TypeError: custom_do_this() takes no arguments (1 given)
Why am I getting it?It's the same thing, no difference.
Also how can I do this in new style class (inherited from 'object')?
--
Gabriel Genellina