Create a class at run-time

I V ivlenin at gmail.com
Fri Mar 26 02:53:04 CET 2010


On Thu, 25 Mar 2010 15:00:35 -0700, Michel wrote:
> 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:

I'm not entirely sure what you mean by binding methods to the instance. 
Do you mean you need to dynamically add methods to a specific instance? 
Or that you need to add methods to a class, such that they can be invoked 
on specific instances? For the latter, just do:

TestClass.test_foo = test_foo

For the former, try:

tc = TestClass()
tc.test_foo = types.MethodType(test_foo, tc)



More information about the Python-list mailing list