Dynamic classes

Alex Martelli aleax at mail.comcast.net
Fri Nov 25 12:30:00 EST 2005


Dave Rose <s_david_rose at hotmail.com> wrote:

> Hello all.
>   I was wondering if creating classes could be dynamic.  I want to know if I
> can make a class Person, then read in a list of names (say people's names)
> so then I can have a class instance created for each name in the list?

Yes, but what you're asking for in your second sentence is different
from what you're wondering about in your first one.

You can create a class dynamically.
You can create dynamically an instance of a class.
The two things are quite separate issues.

You create a new class each time you execute a 'class' statement, or
call 'type' (or other custom metaclass) with suitable arguments.  You
can do either or both in the body of a loop over a list of names, say.

You create a new instance of a class each time you call the class.
Again, of course you can do this in a loop's body.

Creating new classes is a reasonably rare need, creating new instances
is a very common need.  Perhaps you can clarify which one you mean?


Alex



More information about the Python-list mailing list