How best to dynamically define methods (and functions)?

Diez B. Roggisch deets at nospam.web.de
Sun Sep 2 04:22:55 EDT 2007


Kenneth McDonald schrieb:
> I can see an obvious but hacky way to define a Python function at 
> runtime. I can't see any obvious way to add a method to a class at 
> runtime (though I'm sure one could do just about anything by digging 
> into the metaclass stuff, which I will do if needed). But pointers to 
> cleaner or easier existing ways to do this would be most appreciated.
> 
> In case it's of interest in the context of the question, I need to 
> define a largish set of functions (and similar methods) that define a 
> XML-type markup language. Most of these functions will just be of the form
> 
> def fun(...):
>    return Node('fun', ...)
> 
> so it'd definitely be nice to just create most of them automatically, 
> and only do the special cases by hand.

Then don't do it that way, but use __getattr__. It will exactly do what 
you want:


class Foo(object):
    def __getattr__(self, name):
        return Node(name, ....)


    def some_node(self):
        ... # hand coded stuff


Diez



More information about the Python-list mailing list