how to dynamically create class methods ?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Tue Mar 25 23:55:00 CET 2008


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)
    


-- 
Steven



More information about the Python-list mailing list