Thursday, June 18, 2009

Dynamically create a type with Python

Create new type on the fly with type in Python Code:
def cat_init(self):
    self.test1 = '1'
    self.test2 = '2'

def some_method(self):
    print 'meow'

# create new class on the fly
Cat = type('Cat', (object,), {'meow': some_method, '__init__': cat_init })

# create instance of the new class
cat = Cat()

# test new instance
print cat.test2
# >>> 2
print cat.test1
# >>> 1
cat.meow()
# >>> meow