En Tue, 29 Jul 2008 01:17:13 -0300, Piyush Anonymous
<piyush.subscri ption@gmail.com escribi�:
You forget the self argument (this explains the error you got).
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:
pyo = MyObject("hello ")
pyMyObject.cust om_do_this = custom_do_this
pyo.custom_do_t his()
custom do_this implementation for hello
new.instancemet hod is useful to add specific methods to individual
instances, but it's not used to add methods globally to the class.
Add the self argument and you're done.
It's the same thing, no difference.
--
Gabriel Genellina
<piyush.subscri ption@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
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
"""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
namespace:
setattr(clas, method_name, func)
If you know the name when you write the code, just set the attribute:
pyo = MyObject("hello ")
pyMyObject.cust om_do_this = custom_do_this
pyo.custom_do_t his()
custom do_this implementation for hello
new.instancemet hod 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)
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')?
>
Also how can I do this in new style class (inherited from 'object')?
--
Gabriel Genellina