Dynamic classes

Piet van Oostrum piet at cs.uu.nl
Fri Nov 25 13:07:36 EST 2005


>>>>> "Dave Rose" <s_david_rose at hotmail.com> (DR) wrote:

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

If you have the class Person, you are not creating it dynamically. And of
course you can create instances dynamically as you describe.

>DR>   Why do I want to do this?  I was just thinking if I had a name on the 
>DR> list, Dave, I could then be able to read the name in the list, and
>DR> assign Maria.birthday = <> and all the other attributes I would want
>DR> to use a class for, except this is dynamic. I don't know how to
>DR> iterate thru the list to assign the different attributes yet, but this
>DR> seemed reasonable to want to do, and thought I could learn from this.

If I understand you correctly, you want to create a variable with name
'Maria' when you read the name "Maria". Creating variables dynamically is
possible in Python but is almost always the wrong thing to do. Instead it
is usually better to use a dictionary.

class Person:
      def __init__(self, name):
          self.name = name

persons = {}

now you have a loop that reads persons' names, say in name.

myperson = persons[name] = Person(name)

Now I suppose you want to read additional attributes, while the list of
possible attributes is in principle open.

So suppose you have read the attribute name in attr and the value in val.
The you can dynamically create an instance attribute with:

setattr(myperson, attr, val)
-- 
Piet van Oostrum <piet at cs.uu.nl>
URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org



More information about the Python-list mailing list