Adding a method to an instance
Rainer Deyke
root at rainerdeyke.com
Sat Mar 3 13:14:37 EST 2001
"Bryan Mongeau" <bryan at eevolved.com> wrote in message
news:G2%n6.360714$JT5.11606234 at news20.bellglobal.com...
> Quick one for you guys:
>
> I would like to add a method to an instantiated class.
>
> class foo:
> def __init__(self):
> self.bar = 123
>
> f = foo()
>
> Now to add a method to the instance f of class foo:
>
> def newMethod(self):
> print self.bar
In this particular case:
f = foo()
def newMethod(self=f):
print self.bar
f.newMethod = newMethod
In general:
def add_method(instance, method, name):
# We want nested scopes! We want nested scopes! We want nested scopes
# In the absence of nested scopes, there is no easy way to pass on
# non-keyword args to 'method'.
def call_method(instance=instance, method=method, **kwargs):
method(instance, **kwargs)
setattr(instance, name, call_method)
add_method(f, newMethod, 'newMethod')
--
Rainer Deyke (root at rainerdeyke.com)
Shareware computer games - http://rainerdeyke.com
"In ihren Reihen zu stehen heisst unter Feinden zu kaempfen" - Abigor
More information about the Python-list
mailing list