[Tutor] Instantiating large numbers of objects? [lists and dictionaries]
Britt Green
cheshire_cat_sf@yahoo.com
Sun, 3 Feb 2002 21:08:58 -0800 (PST)
Hello,
After playing with this code, I've got a few questions I was hoping you
could help me out with.
--- Danny Yoo <dyoo@hkn.eecs.berkeley.edu> wrote:
<snip>
> ###
> >>> class Person:
> ... def __init__(self, name):
> ... self.name = name
> ... def sing(self):
> ... print "tra la la, my name is", self.name
> ...
> >>> names = ['bart', 'lisa', 'marge', 'homer']
> >>> people = []
> >>> for n in names:
> ... people.append(Person(n))
> ...
Just wondering how this last line works. I've only created instances
of a class by going:
>>>lisa = Person()
Apparently when you're adding classes to a list, the syntax is
different? Do I understand this correctly?
<snip>
> That is, it might be nice to use the person's name to pull them from
> our
> list container. In that case, we can use a more appropriate data
> structure, the dictionary:
>
> ###
> >>> people_dict = {}
> >>> for n in names:
> ... people_dict[n] = Person(n)
> ...
> >>> people_dict['lisa'].sing()
> tra la la, my name is lisa
> ###
Again, the syntax is a little different than what I'm used to. I've
always never seen a dictionary done like this. Is it a case where the
syntax is different since its being added to a list?
Thanks!
Britt
=====
"The ocean, she is strange and wondrous, filled with animals that disturb even a Frenchman."
__________________________________________________
Do You Yahoo!?
Great stuff seeking new owners in Yahoo! Auctions!
http://auctions.yahoo.com