convert string to a method of a class at runtime?
Andrew Dalke
dalke at dalkescientific.com
Sun Jun 2 17:24:40 EDT 2002
Kevin Altis:
>I would like to be able to take a string containing the definition of a
>method, compile the method and then add it to an instance variable at
>runtime, so that the method defined in the string is part of the class just
>as if it had actually been in the class definition to begin with when the
>module was first used.
I am wary about using such tricks. Still, try this approach instead
>>> class H:
... def hello(self, s):
... print s
...
>>> h = H()
>>> h.hello('world')
world
>>> s = """def world(self, s):
... print s
...
... """
>>> d = {}
>>> exec s in d
>>> H.world = d["world"]
>>> h.world('new world')
new world
>>>
Andrew
dalke at dalkescientific.com
More information about the Python-list
mailing list