[BangPypers] Tip: Creating new classes on the fly

Jeffrey Jose jeffjosejeff at gmail.com
Sat Jul 24 12:20:05 CEST 2010


On Tue, Jul 20, 2010 at 9:56 AM, Roshan Mathews <rmathews at gmail.com> wrote:

> 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())
>

What you mentioned here is the exact mechanism of a instantiation of a class
by metaclass.
Here class is `Bar` and MetaClass is `type`

Normally,
clsObj = Class() #l = list(), d = dict() etc


and for instantiaing Class,

Class = Metaclass(Class.__name__, bases, 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?
>

Nope, I'm stuck with 2.5 for a while at work.


More information about the BangPypers mailing list