[Tutor] Ideas on making this cleaner?

Alan Gauld alan.gauld at yahoo.co.uk
Sat May 4 18:42:33 EDT 2024


On 04/05/2024 20:44, Leam Hall wrote:

> TBQ, the Report class is a builder inside the Chapter class. 

I think the question is, why a class and not just a function?
You could just have a report module with a report_data() function
that takes the same inputs as the constructor. There is no real
value in creating an instance of the class since it does not
hold any useful state(the individual reports could be created
on demand) The argument for retaining a class is if you
subsequently compare different chapter reports but then
there should be comparison methods in the class...

So arguably you could clean up the code by removing the
class and just making a module with a set of functions.

BTW. For a slightly different solution to a very similar problem
check out the grammar checker case study in my tutorial...
It doesn't do the "level report" but it does count the
various grammar parts. It uses regex for the punctuation/splitting etc

> ...The report data gets called by they Chapter class, and 
> is later written to a report file.

So where is the method for writing it to a file? eg:

def store(self, filename=self.filename):...

Finally, a tiny bit of clean up would be to use a list
comp to populate lines:

class Report:
     def __init__(self, data, filename):
         self.filename = filename
         self.lines = list()
         for line in data:
             self.lines.append(line.lower())
         ...

Becomes:

class Report:
     def __init__(self, data, filename):
         self.filename = filename
         self.lines = [line.lower for line in data]
         ...

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos





More information about the Tutor mailing list