Create a class at run-time

Patrick Maupin pmaupin at gmail.com
Thu Mar 25 23:34:32 CET 2010


On Mar 25, 5:00 pm, Michel <michel.metz... at gmail.com> wrote:
> 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:

Well, you should just fill your empty dict with function definitions,
BEFORE you build the class.  That's easiest.  Also, you can just use
type:

def foo(*whatever):
    print foo

bar = type('MyDynamicClass', (object,), dict(foo=foo))

HTH,
Pat



More information about the Python-list mailing list