[Tutor] Creating instances (group program revisited)

Daniel Yoo dyoo@hkn.eecs.berkeley.edu
Tue, 27 Mar 2001 10:44:22 -0800 (PST)


On Mon, 26 Mar 2001, Timothy Wilson wrote:

> Here's the question. I think the loadFile method creates a Student instance
> for each line in the datafile, but I'm puzzles about how I'm going to
> reference those instances later. Essentially, this is why a previous
> incarnation had a Roster class which functioned as a container for all the
> Student objects. Would someone care to comment on this?

Let's take a look.


> def loadFile(datafile):
> 	f = open(datafile, 'r')
> 	nameList = f.readlines()
> 	for i in nameList:
> 		Student(i)

So we're definitely constructing a student for every line in your
datafile... but we need to capture the student, to put it in some sort of
container.  Otherwise, you're right --- there's no way to get at any
particular student anymore, since we don't have a name for it.

We could do something like this:

def loadFile(datafile):
	f = open(datafile, 'r')
	nameList = f.readlines()
        students = []
	for i in nameList:
		students.append(Student(i))
	return students        

in which case, we use a list to store all the students, and return that
back as loadFile's return value.