Entry
Creating class instances in batch
Mar 4th, 2004 00:07
Martin Miller, Nathan Wallace, Hans Nowak, Snippet 20, Gordon McMillan
"""
Packages: oop
"""
"""
> BUT How to create class instances in batch? I have search the
> documentation but failed to find any clue.
>
> Here is what I have tried.
>
> With this list of [name, age] pairs, a = [ ['Clinton', 55],
> ['Star', 54], ['Hillary', 53], ........ ] and class
>
> class Person:
> def __init__(self, age):
> self.age = age
>
> I want to do something like this in effect.
> Clinton = Person(55); Star = Person(54); Hillary = Person(53) ...
Normally, you would define person as
"""
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
#more stuff
people = []
for (name, age) in [('Clinton', 55), ('Hillary', 53) # (...) etc
]:
people.append(Person(name, age))
"""
or, perhaps
people = {}
for (name, age) in ...:
people[name] = Person(name, age)
It doesn't make much sense to bind your Person instance to the
person's name - interactively that helps you remember which instance
is which, but it really doesn't help in a script. If you put all your
instances in some kind of container, it'll make them much easier to
deal with.
"""