Add methods to a class dynamically

Damien Metzler dmetler.nospam at partner.auchan.fr
Fri Jun 6 16:49:18 CEST 2003


Hoang Do wrote:
> I am having trouble invoking the created method.  The function addition goes
> fine but invoking it gives an error.  Here is some simple code:
> ---------------------------------------------------------
> class DynObj:
>     def __init__(self):
>         self.methods = ("a", "b", "c")
>         for method in self.methods:
>            self. __generateMethod(method)
>     def __generateMethod(self, methodName):
>         code = "def %s(self):\n\tprint %s\n" % (methodName, methodName)
>         exec code in globals(), self.__dict__
> 
> if __name__ == "__main__":
>     x = DynObj()
>     print dir(x)
>     x.a(x)
> ---------------------------------------------------------
> The Error:
> NameError: global name 'a' is not defined
> ---------------------------------------------------------
> Methods "a", "b", and "c" are callable and in DynObj's __dict__.  However, I
> can't seem to call it.
> 
> Calling for help from anyone familiar with Python's introspective features?



code = "def %s(self):\n\tprint '%s'\n" % (methodName, methodName)

you forgot the ' so your looking to print the variable a wich is not 
defined as a global variable





More information about the Python-list mailing list