Best way to create a class dynamically on the fly?

Evan evan at 4-am.com
Sat Sep 28 21:02:17 EDT 2002


Robert Oschler wrote:
> What is the best way to create a Python class dynamically at runtime?

ALL Python classes are created dynamically at runtime.  The following is 
not a declaration in the sense that you're accustomed to from C/C++, it 
is normal code executed when the containing file is run (or imported):

class Foo:
   def meth1(self):
     return "I am a method"

Your class definition can include whatever Python code you need, and it 
doesn't have to be at global module level:

def makeFoo(x):
   class Foo:
     sharedValue = x * 2
     if x > 2:
       def manymethod(self, i):
         return i + 3
     else:
       def fewmethod(self, i):
         return i + 1
   return Foo

Foo = makeFoo(4)
f1 = Foo()
print f1.sharedValue, f1.manymethod(2)

Cheers,

Evan @ 4-am




More information about the Python-list mailing list