Creating new classes on the fly
Alex Martelli
aleaxit at yahoo.com
Thu Oct 7 03:42:02 EDT 2004
Carlos Ribeiro <carribeiro at gmail.com> wrote:
> I need to create new classes on the fly with different default
> parameters, stored as class attributes. Of course, there's a reason
> behind it: I need new classes, because I need to be able to build
> multiple instances of them later. And I need new defaults, because the
> values can't be provided at instantiation time (because of scoping &
> mutability issues).
>
> I've found two different ways to do it in the documentation:
>
> new.classobj(name, baseclasses, dict)
This normally makes a 'classic class', unless some baseclasses are
non-classic (e.g., object or other built-ins); note that __metaclass__
in dict is ignored.
>
> and:
>
> type(name, bases, dict)
This makes a new-style class (again, __metaclass__ in dict is ignored).
>
> I assume that both end up calling the same code, but I really don't
> know which one am I supposed to call, in terms of being the most
> 'pythonic' way. Are both the same? Is one of them preferred over the
> other?
They're not quite the same, if the bases tuple is empty or only has
classic classes. I would normally use the second form because new-style
classes are generally preferred.
Alex
More information about the Python-list
mailing list