Create a class at run-time
Michel
michel.metzger at gmail.com
Thu Mar 25 18:00:35 EDT 2010
Hi everyone,
I'm trying to dynamically create a class. What I need is to define a
class, add methods to it and later instantiate this class. Methods
need to be bound to the instance though, and that's my problem. Here
is what I have so far:
method_template = "def test_foo(self):\
#actual test_foo\
pass"
exec method_template
TestClass = types.ClassType("MyTestClass", (unittest.TestCase, ), {})
TestClass.__module__ = "test"
now what to do next?
I looked at types.MethodType but it needs an instance to bind the
method and a function object.
Should I define __new__ to bind the method during instantiation?
Hope this makes sense,
Michel.
More information about the Python-list
mailing list