A List of Class Objects (Python)

vegaseat 2 Tallied Votes 124K Views Share

A list of class objects mimics a C array of structures. The snippet explores how to setup the list, and sort the list according to a selected attribute. Then we use a format string to display the sorted list. Take a look at how to search the list. All in all an easy way to handle structured data.

# 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"""
    def __init__(self, name=None, job=None, quote=None):
        self.name = name
        self.job = job
        self.quote = quote
        
print

# make a list of class Person(s)
personList = []
personList.append(Person("Payne N. Diaz", "coach", "Without exception, there is no rule!"))
personList.append(Person("Mia Serts", "bicyclist", "If the world didn't suck, we'd all fall off!"))
personList.append(Person("Don B. Sanosi", "teacher", "Work real hard while you wait and good things will come to you!"))
personList.append(Person("Hugh Jorgan", "organist", "Age is a very high price to pay for maturity."))
personList.append(Person("Herasmus B. Dragon", "dentist", "Enough people can't find work in America!"))
personList.append(Person("Adolph Koors", "master-brewer", "Wish you were beer!"))
personList.append(Person("Zucker Zahn", "dentist", "If you drink from the fountain of knowledge, quench your thirst slowly."))

print "Show one particular item:"
print personList[0].name

print

print "Sort the personList in place by job ..."
import operator
personList.sort(key=operator.attrgetter('job'))

print "... then show all quotes and who said so:"
for person in personList:
    print "\"%s\"  %s (%s)" % (person.quote, person.name, person.job)
    
print

print "Show the quote(s) from any dentist:"
look = 'dentist'
for person in personList:
    if look in person.job:
        # title() capitalizes the job's first letter
        print "%s %s: \"%s\"" % (person.job.title(), person.name, person.quote)
        
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)
ee_programmer 0 Newbie Poster

Using python2.4 and I'm getting unexpected results when a dictionary is an element of a class, where all class instances access a single shared hash rather than each class instance having their own separate hash. Modifying the above example. (Apologies if my code formatting is wrong, I haven't posted before)

class Person(object):
def __init__(self, name=None, job=None, quote=None, hash={}) :
         self.name = name
         self.job = job
         self.quote = quote
         self.hash = hash

#create an empty list
personList = []

#create two class instances
personList.append(Person("Payne N. Diaz", "coach", "Without exception, there is no rule!"))
personList.append(Person("Mia Serts", "bicyclist", "If the world didn't suck, we'd all fall off!"))

# assign a single entry to the dictionary of each class instance
personList[0].hash['person0'] = 0
personList[1].hash['person1'] = 1

# print dictionary of first class instance
print personList[0].hash
{'person0': 0, 'person1': 1}

# print dictionary of second class instance
print personList[1].hash
{'person0': 0, 'person1': 1}

I was expecting the first class instance to only have one dictionary entry
{'person0': 0} rather than two dictionary entries. Similar expectation with second
class instance.

How do I create and assign value to separate dictionaries for each class instance?

Thanks-
ee_programmer

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

ee_programmer, I posted the answer in the Python forum so the format is proper.
Thread title: A List of Class Objects

lupond 0 Newbie Poster

how do I develop a program that calculate class average for each of the three tests for a class of 20 students and the program should also calculate the average of each of the student scores in those three test. Should also display the results in descending order per test i.e a student name and the corresponding test result of the student.

Editor's note:
There is a difference between a class of students and a Python class. This kind of homework question hardly belongs here. Please start your own properly titled thread in the regular Python forum! Also show some coding effort.

Shreyaa 0 Newbie Poster

Can u please tell me if this sort of declaration work?

a = []
log = []
b = []
l = []
assignment(a,log, b, l)

def assignment(a,log,b,l):
insname = open("3ope.txt",'r')
        ct=-1
        string=insname.readline()
        while string!=" ": file:
                a.append(instruction())
                a[ct+1].inst=string# considering the class has inst ATTRIBUTE
                string=insname.readline()
Gribouillis 1,391 Programming Explorer Team Colleague

@Shreyaa In principle it works, but it would be written more pythonically this way

def assignment(a, log, b, l):
    with(open("3ope.txt",'r')) as insname:
        for line in insname:
            a.append(instruction())
            # .rstrip() removes white space at the end of the line
            a[-1].inst = line.rstrip()

For python code, configure your editor to insert 4 space characters for indentation (when you hit the tab key).

Also, if you have more questions, start your own discussion thread instead of reviving old threads !

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.