[BangPypers] Tip: Creating new classes on the fly

Roshan Mathews rmathews at gmail.com
Tue Jul 20 06:26:30 CEST 2010


I came across this in a blog post just now.
See http://docs.python.org/library/functions.html#type

>>> class Foo(object): pass
...
>>> Bar = type('Bar', (object,), dict())
>>> f = Foo(); b = Bar()
>>> type(f), type(b)
(<class '__main__.Foo'>, <class '__main__.Bar'>)

Also see http://docs.python.org/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields

>>> from collections import namedtuple
>>> Baz = namedtuple('Baz', '')

Anyone switched to Python 2.7 yet?

-- 
http://roshan.mathews.in/


More information about the BangPypers mailing list