And while we are 'at it' ... i.e. Python Classes ...
here are two more related little 'demo programs' that illustrate overloading (in Python 3) ...
# testClassIter.py # 2013-03-01 #
class Student( object ):
count = 0
def __init__(self, idNum =0, name ='', subjectMarks =()):
self.idNum = idNum
self.name = name
self.subjectMarks = subjectMarks
Student.count += 1
def __str__(self):
return 'ID: {:>2d} NAME: {:<16s} AVERAGE: {:>5.1f} \n{}'\
.format(self.idNum,self.name,self.getAvg(),self.subjectMarks)
def __iter__(self):
self.index = 0
return self
def __next__(self):
self.index += 1
if self.index == 1: return self.idNum
if self.index == 2: return self.name
if self.index == 3: return self.subjectMarks
raise StopIteration
def __getitem__(self, index):
if index == 0: return self.idNum
if index == 1: return self.name
if index == 2: return self.subjectMarks
def __del__(self):
Student.count -= 1
print( '\n del was called ...' )
def getAvg(self):
if self.subjectMarks:
return sum(x[1] for x in \
self.subjectMarks)/len(self.subjectMarks)
else:
return 0
s1 = Student( 1, 'Sam', (('Math',99),('History',77),('English',69)) )
studs = [s1]
print( 'Student.count =', Student.count )
print( s1 )
for i, item in enumerate(s1):
if i < 2:
print( item )
else:
for element in item:
print( element[0], '=', element[1] );
print( 's1.getAvg() = {:.1f}'.format(s1.getAvg()) )
def addStud():
s2 = Student( 2, 'Sally', (('Math',100),('History',100),('English',100)) )
print( '\nStudent.count =', Student.count )
print( s2 )
for i, item in enumerate(s2):
if i < 2:
print( item )
else:
for element in item:
print( element[0], '=', element[1] )
print( 's2.getAvg() = {:.1f}'.format(s2.getAvg()) )
#studs.append(s2)
addStud()
print( '\nStudent.count =', Student.count )
def add2():
global studs
studs.append( \
Student(3, 'Ally', (('Linear Algebra',100), \
('Calculus',100), ('Physics',100))) )
studs.append( \
Student(4, 'Ally', (('Linear Algebra',99), \
('Calculus',98), ('Physics',88), ('Chem 201', 93))) )
print( "\nSorting by avg's using "\
"studs.sort( key = Student.getAvg, reverse = True )")
studs.sort( key = Student.getAvg, reverse = True )
for s in studs:
print( s )
print( "\nSorting by names using "\
"studs.sort( key = itemgetter(1,0), reverse = True )")
from operator import itemgetter
studs.sort( key = itemgetter(1,0), reverse = True )
print( '\nStudent.count =', Student.count )
for s in studs:
print( s )
studs = studs[0:1]
add2()
print( '\nStudent.count =', Student.count )
input( "\nPress 'Enter' to continue/exit ... ")
Now ... using a Python dictionary ...
# testClassIterDict.py # 2013-03-01 #
class Student( object ):
count = 0
def __init__(self, idNum =0, name ='', subjectMarks ={}):
self.idNum = idNum
self.name = name
self.subjectMarks = subjectMarks
Student.count += 1
def __str__(self):
return 'ID: {:>2d} NAME: {:<16s} AVERAGE: {:>5.1f} \n{}'\
.format(self.idNum,self.name,self.getAvg(),\
sorted(self.subjectMarks.items()))
def __iter__(self):
self.index = 0
return self
def __next__(self):
self.index += 1
if self.index == 1: return self.idNum
if self.index == 2: return self.name
if self.index == 3: return self.subjectMarks
raise StopIteration
def __getitem__(self, index):
if index == 0: return self.idNum
if index == 1: return self.name
if index == 2: return self.subjectMarks
def __del__(self):
Student.count -= 1
print( '\n del was called ...' )
def getAvg(self):
if self.subjectMarks:
return sum(v for v in self.subjectMarks.values()) \
/len(self.subjectMarks)
else:
return 0
s1 = Student( 1, 'Sam', dict(Math=99, History=77, English=69) )
studs = [s1]
print( 'Student.count =', Student.count )
print( s1 )
for i, item in enumerate(s1):
if i < 2:
print( item )
else:
for k, v in sorted(item.items()):
print( k, '=', v )
print( 's1.getAvg() = {:.1f}'.format(s1.getAvg()) )
def addStud():
s2 = Student( 2, 'Sally', dict(Math =100, History =100, English =100) )
print( '\nStudent.count =', Student.count )
print( s2 )
for i, item in enumerate(s2):
if i < 2:
print( item )
else:
for k, v in sorted(item.items()):
print( k, '=', v )
print( 's2.getAvg() = {:.1f}'.format(s2.getAvg()) )
#studs.append(s2)
addStud()
print( '\nStudent.count =', Student.count )
studs.append( Student(3, 'Ally', dict(Linear_Algebra =100, Calculus =100, \
Physics =100)) )
studs.append( Student(4, 'Ally', dict(Linear_Algebra =99, Calculus =98, \
Physics =88, Chem_201 =93)) )
print( "\nSorting by avg's using "\
"studs.sort( key = Student.getAvg, reverse = True )")
studs.sort( key = Student.getAvg, reverse = True )
for s in studs:
print( s )
print( "\nSorting by names using "\
"studs.sort( key = itemgetter(1,0), reverse = True )")
from operator import itemgetter
studs.sort( key = itemgetter(1,0), reverse = True )
for s in studs:
print( s )
input( "\nPress 'Enter' to continue/exit ... ")