[Tutor] List of Classes with a dictionary within the Class.
Mukund Chavan
mukundc at hotmail.com
Wed Sep 21 23:57:06 CEST 2011
Hi,
I was trying to get a list of Class Objects.
The Class itself has string fields and a dictionary that is initialized as a part of the "__init__"
However the fields of the dictionary for each object in the list of class objects seems to be the same.
I took an example from the following site:
"http://www.daniweb.com/software-development/python/code/216631" and modified it. The code is cut/pasted below
with the result of the run immediately following. I expected the 4th and 5th column in the output to be unique, but
they seem to get the value of the last item in the iter range.
I am running "Python 2.6.5" on Ubuntu 10.04 TLS-64bit.
Thanks in advance.
- Mukund
Code:
----<snip>----
#!/usr/bin/python
#a list of class objects to mimic a C type array of structures
# tested with Python24 vegaseat 30sep2005
class Person(object):
"""__init__() functions as the class constructor"""
personAttrs={"'num1":"","num1":""}
def __init__(self, name=None, job=None, quote=None, num1=None, num2=None):
self.name = name
self.job = job
self.quote = quote
self.personAttrs["num1"]=num1
self.personAttrs["num2"]=num2
print
# make a list of class Person(s)
personList = []
for i in range(4):
personList.append(Person("M",i,"XYZ",-i,i))
print "Show one particular item:"
print personList[0].name
print
print "... then show all quotes and who said so:"
for person in personList:
print "\"%s\" %s (%s) %s %s" % (person.quote, person.name, person.job,str(person.personAttrs['num1']),str(person.personAttrs['num2']))
print
print "What the heck did the person named Sanosi say?"
look = "Sanosi"
for person in personList:
if look in person.name:
print "%s: \"%s\"" % (person.name, person.quote)
----<snip>----
Output:
----<snip>----
Show one particular item:
M
... then show all quotes and who said so:
"XYZ" M (0) -3 3
"XYZ" M (1) -3 3
"XYZ" M (2) -3 3
"XYZ" M (3) -3 3
What the heck did the person named Sanosi say?
----<snip>----
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110921/2226435e/attachment.html>
More information about the Tutor
mailing list