I have the following code, where I use a class stat to keep my data. Objects of type stat are inserted in a list. However, when I try to call the method printStats, I get the error, AttributeError: stat instance has no attribute 'printStats'. Secondly I want to know how can I sort the list containing objects of stat. My sorting should be based on the blocks field of stat.
fi = open( 'txt/stats.txt', 'r' )
fo = open( 'compile/stats.txt', 'w' )
list = []
class stat():
def __init__(self, fname, blocks, backEdges):
self.fname = fname
self.blocks = blocks
self.backEdges = backEdges
def printStats(self):
print self.fname + str(self.blocks) + str(self.backEdges)
while True:
line_str = fi.readline()
if line_str == '':
break
str = line_str.split()
list.append( stat(str[0], int(str[1]), int(str[2])) )
for item in list:
item.printStats() # <-- problem calling this
As far as the sorting is concerned, you definitely can use the
keyfunction:However, if you want to be able to compare
statsobjects in a non-sorting context, you can override__eq__,__gt__,__lt__(and to make your life easier, you can use the functools.total_ordering class decorator to define most of the comparisons for you):with
statsdefined this way, sorting should again be as simple as: