Add methods to a class dynamically

Hoang Do tr at jotsite.com
Fri Jun 6 13:25:14 EDT 2003


Thank you for the reply.  That was the answer.  I forgot to quote my print
statement and the error message from the interpreter was misleading.

I'm also posting from Google so my response might be slow.

Damien Metzler <dmetler.nospam at partner.auchan.fr> wrote in message news:<bbq8rb$glb$1 at reader1.imaginet.fr>...
> 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