Dynamically adding methods to objects?
Jacek Generowicz
jacek.generowicz at cern.ch
Mon Jun 7 03:32:00 EDT 2004
Carl Banks <imbosol at aerojockey.invalid> writes:
> John Roth wrote:
> > "Holger T?rk" <htx1 at gmx.de> wrote in message
> > news:c9um21$hca$03$1 at news.t-online.com...
> >> damian birchler wrote:
[ f = Foo() ]
> >> > I know how to do it manually, I just define a function and assigne it
> >> > to f -
> >> >
> >> > def bar():
> >> > pass
> >> >
> >> > f.bar = bar -,
> >> > but what if this should be done at runtime. How can I get the string
> >> > passed to f.add_function as name to be the name of a new function in
> >> > the function's definiton?
> >>
> >> f.bar = bar is the same as setattr (f, "bar", bar)
> >>
> >> Remember that bar does not become a method of f, but remains
> >> only a function which is stored in f. Is not subject of the
> >> binding of the "self" parameter.
> >
> > Ah, but that's what I want to do - have a ***method***
> > where the self parameter works the way I expect it to.
>
>
> Is this what you want?
>
> def selfize(obj,func):
> def callfunc(*args,**kwargs):
> func(obj,*args,**kwargs)
> return callfunc
>
> f.bar = withself(f,bar)
What's "withself" ?
Isn't John saying he wants exactly what the instancemethod function in
the new module was designed for:
import new
f.bar = new.instancemethod(bar, f, Foo)
?
More information about the Python-list
mailing list