Dynamically adding methods to a class...

Piyush Anonymous piyush.subscription at gmail.com
Tue Jul 29 00:17:13 EDT 2008


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


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


myobj = MyObject('myobj1')
funcToMethod(custom_do_this,MyObject) #trying 2 add method to class not
instance
print myobj.custom_do_this()

---
Error I am getting;
TypeError: custom_do_this() takes no arguments (1 given)

Why am I getting it?

Also how can I do this in new style class (inherited from 'object')?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080729/2c4080d2/attachment.html>


More information about the Python-list mailing list