[Tutor] Class
Alan Gauld
alan.gauld@blueyonder.co.uk
Wed Jun 18 15:17:02 2003
> hey i was wondering how do you write a class ??
You will find more details in the OO section of my online
tutor (see below), however...
> class Diary:
Good start!
> def __init__(self):
> self.data = []
THis needs to be indented to tell Python that its actually
part of the class. And probably something like "entries" is a
better name than 'data' whoich doesn't really tell us what
kind of data...
> def addEntry(day, month, year, text):
You need to have a self parameter at the start of methods.
This will, when the method is executed, comntain a refeence
to the actual instance of diary that is being used.
You can then use that self reference to access your data/entries list:
def addEntry(self, day, month, year, text):
self.data.append((day,month, year, text))
Another way to do this though would be to use a dictionary
keyed by date.
def __init__(self):
self.entries = {}
def addEntry(self, theDate, theText)
self.entries[theDate] = theText
Then extracting an entry becomes a case of accessing the
dictionary:
def readEntry(self, aDate):
return self.entries[aDate]
Of course you probably want the ability to append edditional
text to a date:
def appendEntry(self, theDate, theTExt):
self.entries[theDate] = self.entries[theDate] + theTExt
You can either use the mxDate module to generate and manipulate
dates, or the standard time library module might suffice. Although
for the latter I'd be inclined to create a Date class to wrap it up
more conveniently. Overall I'd recommemd mxDate I think...
HTH,
Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld