[Tutor] Creating instances (group program revisited)
Benoit Dupire
bdupire@seatech.fau.edu
Tue, 27 Mar 2001 00:25:41 -0500
This is How I would solve the pb.
In fact, I don't think you have to have a 'Class' class, because the Class is
what you want to model. It's the whole!
Instead of the word 'class', I ll use 'course' because it is confusing with the
OO terminology...
What you want to model is what a course id ?
The first actor is the teacher...
Yes.. because the teacher is going to make the group, not the students nor the
'course'....
A teacher has some the students.
A teacher can make some groups, print the list of his students, and introduce
himself!
He can add some students to his course...
Note1 : if you want your pb to be really OO, put the loadFile function in a
class... (see below1)
Note2: it's better to have the split() logic in the loadFile function: the file
has to be decoded in this function because if you want to store the student
names with a different syntax, what you really want to do is to modify the
loadFile function and not the Student __init__ function.
In OO you have to define interfaces, that 's the encapsulation principle.
Now if i change something, it's very 'local'...
import string
class Student:
def __init__(self, ln, fn, gender):
self.ln = ln
self.fn = fn
self.gender = gender
self.group= 0
def getName(self):
return self.ln
def __str__(self):
return "%(ln)s %(fn)s %(gender)sin group: %(group)i" %self.__dict__
def setGroup(self, groupNumber):
self.group= groupNumber
class Teacher:
def __init__(self, name):
self.name=name
self.studentList= []
self.nbStudent = 0
def __str__(self):
return "My name is %s and my class has %i students" %(self.name,
self.nbStudent)
def addStudentFromFile(self, datafile):
list= open(datafile, 'r').readlines()
for entry in list:
ln, fn, gender = entry.split(',')
self.studentList.append(Student(ln, fn, gender))
self.nbStudent+=len(list)
def makeGroup(self, nbgroup):
i=0
for st in self.studentList:
st.setGroup(i % nbgroup)
i+=1
def printStudentList(self):
for st in self.studentList:
print st
thePythonTeacher= Teacher('timothy')
thePythonTeacher.addStudentFromFile('toto.txt')
print thePythonTeacher
thePythonTeacher.makeGroup(4)
thePythonTeacher.printStudentList()
>>> reload(student)
My name is timothy and my class has 12 students
van Rossum Guido M
in group: 0
Boop Betty F
in group: 1
Gauld Alan M
in group: 2
Flintstone Wilma F
in group: 3
Rubble Betty F
in group: 0
Yoo Danny M
in group: 1
Wilson Tim M
in group: 2
Crawford Cindy F
in group: 3
Van Laningham Ivan M
in group: 0
Lutz Mark M
in group: 1
Ascher David M
in group: 2
Watters Aaron M
in group: 3
<module 'student' from 'C:\Python20\student.py'>
Yes, I enjoyed playing with your program!
The function to make the group is not perfect, but you end up with
Benoit