Dynamically adding methods to objects?

Carl Banks imbosol at aerojockey.invalid
Sun Jun 6 18:36:07 EDT 2004


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:
>> > 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)


-- 
CARL BANKS                      http://www.aerojockey.com/software
"If you believe in yourself, drink your school, stay on drugs, and
don't do milk, you can get work." 
          -- Parody of Mr. T from a Robert Smigel Cartoon



More information about the Python-list mailing list