Add methods to a class dynamically
Hoang Do
tr at jotsite.com
Fri Jun 6 10:28:54 EDT 2003
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?
More information about the Python-list
mailing list