classes for fun and newbies
Max M
maxm at mxm.dk
Wed Mar 20 09:30:40 EST 2002
Bruce Dykes wrote:
> Now what I expect to be able to do is say:
>
> log = readlines(today.log)
>
> and then summon discrete bits of info like so:
>
> print call_record.record_id(log[1])
It would probably be simpler to it with just a function in this case:
id = (0,5)
date = (6,11)
def getPart(slice, line):
return line(slice[0]:slice[1])
print getPart(id, log[1])
or something like that. But just writing it in one big mess is probably
not out of the question either.
for line in,lines:
id, date = line[0:5], line[6:11]
Generally there is no need ti write objects before it is needed. Ie.
when your code violates the DRY (Dont Repeat Yourself) principle.
But then you could do something like (untested).
class Rec:
def __init__(self, line):
self.line = line
def __getattr__(self, attr):
if attr == 'id':
return self.line[0:5]
if attr == 'date':
return self.line[6:11]
class Log:
def __init__(self, fileName):
f = open(fileName,'r')
self.lines = f.readlines()
f.close()
def __getitem__(self, index):
return Rec(self.lines[index])
def __len__(self):
return len(self.lines)
Then you can use it like:
log = Log('logfile.log')
print log[1].id
or like:
for item in log:
print item.id
regards Max M
More information about the Python-list
mailing list