[Tutor] first program
Sean 'Shaleh' Perry
shalehperry@attbi.com
Tue Jun 24 00:16:02 2003
On Monday 23 June 2003 18:29, mark boydell wrote:
>
> Having written and tested the program it seems to work fine but I've got
> some niggling doubt that I may be breaking some basic rules:
> 1. am I overusing the global scope?
definately. globals are to be avoided. Bad style, hard to debug, etc.
> 2. should I make it more OOP? by making it all into a class?
Dunno, maybe. Below is a rough draft based solely on your code (I tried not
to change much).
> 3. is the general programming style dreadful ;) ?
>
yeah, pretty much (-:
You get points for breaking it into functions but you lose points for the
divisions being arbitrary and for little benefit.
A function should be a block of code you use over and over. Or something that
is easier to write when split off from the whole.
All of your file I/O I would leave in main.
#! /usr/bin/python
class ParseError(Exception):
pass
class ExperimentDate:
def __init__(self, datestring):
self.day = int(datestring[0:2])
self.month = int(datestring[2:4])
self.year = int(datestring[4:])
class DOB:
def __init__(self, datestring, exp):
self.exp_date = exp
self.days = exp.day - (int(datestring[0:2]))
self.months = exp.month - (int(datestring[2:4]))
self.years = exp.year - (int(datestring[4:]))
self.datestring = datestring
def inMonths(self):
months = (self.years * 12) + self.months
if self.days < 16 and self.days > -16:
return months
elif self.days < -15:
return months - 1
else:
return months + 1
def asString(self):
return '%s = %s' % (self.datestring, self.inMonths())
def ioFiles(input):
exp_date = ''
dobList = []
line = input.readline()
if line[0:5] != "date:": #pick out experiment date
raise ParseError
exp_date = line[5:]
dobList = [x.strip() for x in input.readlines()]
return (exp_date, dobList)
def toFile(inputList, exp):
for item in inputList:
dob = DOB(item, exp)
outp.write(dob.asString() + '\n')
if __name__ == '__main__':
import sys
if len(sys.argv) == 2:
fileName = sys.argv[1]
else: # ask for one
fileName = raw_input("file to use? :")
# create the variables etc
inp = open(fileName, "r") # what if the file does not exist?
outp = open("DOBdata.out", "w") # what if you can't create a file?
#call the methods
datestring, dobList = ioFiles(inp)
inp.close()
expDate = ExperimentDate(datestring)
toFile(dobList, expDate)
outp.close()