how to dynamically create class methods ?

jv jgv-home at comcast.net
Tue Mar 25 20:03:40 EDT 2008


Steven D'Aprano wrote:
> On Tue, 25 Mar 2008 14:17:16 -0600, j vickroy wrote:
> 
>> As per your suggestion, I tried looking at include/code.h and
>> include/funcobject.h (my MS Windows distribution does not appear to
>> contain .c files).  However, since I'm not a C programmer, I did not
>> find the .h files all that helpful.
> 
> I'm hardly surprised. The naivety of those who insist that the "best way 
> to understand how new.function and new.code work" is to look at the C 
> source code for object is amusing. Not everybody reads C. This is a 
> Python group, and surely the best way would be to see some good examples 
> using *Python*.
> 
> 
>> What I failed to make clear in my original posting is that the
>> functions must be created dynamically using information in a *record*
>> as the code iterates over all *records*.  So, I can not pre-define the
>> functions and then simply select the desired one at run-time.
> 
> Here's an example that might help.
> 
> 
> class MyClass(object):
>     pass
> 
> records = ["spam", "ham"]
> for record in records:
>     # define a new function
>     def f(n):
>         return (record + " ")*n
>     # create a new instance
>     instance = MyClass()
>     # and dynamically add a method to it
>     setattr(instance, 'execute', f)
>     instance.execute(5)
>     
> 
> 

Gabriel, Steven,

Thanks for taking the time to respond with such clear examples.

All I can say is: "when will I ever learn **everything** in Python is an 
object -- including functions"!  I had a suspicion I was making a simple 
task complicated.

-- jv





More information about the Python-list mailing list