Dynamically adding methods to a class...

arsyed arsyed at gmail.com
Wed Jul 30 07:21:39 CEST 2008


On Tue, Jul 29, 2008 at 12:17 AM, Piyush Anonymous
<piyush.subscription at gmail.com> wrote:
> 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?
>

If your method is going to be bound to an instance, then it needs the
expected signature: the first parameter is always a reference to the
instance ("self").  Change it to "custom_do_this(self)" and it should
work.


> Also how can I do this in new style class (inherited from 'object')?
>
>

What did you try and how did it fail? This seems to work:

def foo(self):
    print 'foo'

class Bar(object):
    pass

Bar.foobar = new.instancemethod(foo, None, Bar)

b = Bar()
b.foobar()







>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list