how to dynamically create class methods ?

Arnaud Delobelle arnodel at googlemail.com
Wed Mar 26 03:27:17 EDT 2008


On Mar 25, 10:55 pm, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> 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.

Since 'those who insist...' are just one person, me, you might as well
name them.  Firstly I didn't 'insist', I stated it once.  Secondly I'm
glad that I provided you with a few chuckles, but to proclaim that one
is 'amused by the naivety of others' doesn't make one automatically
right.

Do you know how these functions behave?  Have you looked at their
documentation?   new.function and new.code (implemented as Objects/
funcobject.c:func_new and Objects/codeobject.c:new_code) are not
really documented (new.code.__doc__ is 'Create a code object.  Not for
the faint of heart.').  If you can't read the source then I don't
think you should use the functions.

> Not everybody reads C. This is a
> Python group, and surely the best way would be to see some good examples
> using *Python*.

And this is what I did in the second part of my post.  I gave an
example which was in essence trying to illustrate the same aspect of
Python as your example, quoted below (namely that you can use 'def' to
create functions on the fly).

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

Amusingly naive'ly yours

--
Arnaud




More information about the Python-list mailing list