Create a class at run-time
michel.metzger at gmail.com
Fri Mar 26 16:54:11 CET 2010
I want to add a method to a class such that it can be invoked on
You solution works (as well as Patrick's one), thanks !
I still have a question though. If I print the type of the self object
I get when my method is
called, I get "<class 'test.TestClass'>". I guess this is because the
method is defined as a class method.
This is ok in my case, but just out of curiosity, what should I do to
change this method to an instance method?
Thanks for your help,
On Mar 25, 9:53 pm, I V <ivle... at gmail.com> wrote:
> 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