classes for fun and newbies
Bruce Dykes
bkd at graphnet.com
Wed Mar 20 10:18:47 EST 2002
----- Original Message -----
From: "Max M" <maxm at mxm.dk>
Newsgroups: comp.lang.python
To: <python-list at python.org>
Sent: Wednesday, March 20, 2002 09:30
Subject: Re: classes for fun and newbies
> 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]
>
> 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
Now, none of these seem as obvious-to-write or as readable-at-a-later-date
as setting each record up as a class first. And setting up the class at the
start seems to be almost self documenting (heck, I *generated* the class
definition from the documentation 8-).
Is there any particular reason to prefer using functions over class
definitions, such as performance, or memory use? Or are we just speaking of
stylistic differences?
> Generally there is no need ti write objects before it is needed. Ie.
> when your code violates the DRY (Dont Repeat Yourself) principle.
As I said, it just seems more natural to me to define each record/line as an
object, with each field being an attribute.
aside: I realize that I'm actually building the guts of a database, but for
something this small, it seems far more efficient to simply write the
necessary text processing and search functions than to build a database in
MySQL or PostgreSQL and then build the necessary connections and filters. A
couple of Python scripts *must* be more lightweight than a fullbore
database.
bkd
More information about the Python-list
mailing list