Dynamically creating classes - Python Dynamically creating classes - Python python python

Dynamically creating classes - Python


You can create classes on the fly by calling the type built-in, passing appropriate arguments along, like:

CommentForm = type("CommentForm", (Form,), {     'name': forms.CharField(),    ...})

It works with new-style classes. I am not sure, whether this would also work with old-style classes.


Classes can be defined almost anywhere.

def newclass(val):  class C(object):    def __str__(self):      return str(val)  return CMyClass = newclass(5)m = MyClass()print str(m)