On Tue, Jul 29, 2008 at 12:17 AM, Piyush Anonymous
<piyush.subscri ption@gmail.com wrote:
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.
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.instancemet hod(foo, None, Bar)
b = Bar()
b.foobar()
<piyush.subscri ption@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(fu nc,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.instancemet hod(func,None,c las)
print method
if not method_name: method_name=fun c.__name__
clas.__dict__[method_name]=func
>
>
myobj = MyObject('myobj 1')
funcToMethod(cu stom_do_this,My Object) #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?
>
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(fu nc,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.instancemet hod(func,None,c las)
print method
if not method_name: method_name=fun c.__name__
clas.__dict__[method_name]=func
>
>
myobj = MyObject('myobj 1')
funcToMethod(cu stom_do_this,My Object) #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?
>
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')?
>
>
>
>
def foo(self):
print 'foo'
class Bar(object):
pass
Bar.foobar = new.instancemet hod(foo, None, Bar)
b = Bar()
b.foobar()