classes for fun and newbies

Max M maxm at mxm.dk
Wed Mar 20 12:20:17 EST 2002


Bruce Dykes wrote:

> From: "Max M" <maxm at mxm.dk>

> 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?


I would choose one over the other for pragmatic reasons. If I was doing 
a one off job I would choose::

for line in lines:
     id, date = line[0:5], line[6:11]
     print id

as it is really simple to write and read. Everybody can understand what 
it does. And It's easy to read later.

On the other hand if you want to use your class as a basis for a whole 
series of script I would use my last approach, with a "list" object 
containing all of the 'records' as this makes for really simple code in 
all of the scripts using the objects.

The first version is easier to write, understand and use, the latter is 
easier to re-user :-/


Your approach is sort of a half-way solution where you are in fact using 
an objects as a "complicated function".


compare:


f = open('today.log', 'r')

log = f.readlines()
print call_record.record_id(log[1])

for rec in log:
     print call_record.record_id(rec)

f.close()



With:


log = Log('today.log')
print log[1].record_id

for rec in log:
     print rec.record_id


I think you will agree that it gives a much cleaner and more readable api.

Especially: call_record.record_id(log[1]) is more convoluted than 
nessecary and sort of counterintuitive. Well at least for me ;-)

There would be nothing wrong with rewriting my "Rec" class to be more in 
line with yours:

class Rec:

     def __init__(self, line):
         self.id   = line[0:5].strip()  # also remove whitespace
         self.date = line[6:11].strip()

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)


Especially if you import the Log class in a lot of other scripts. Then 
all of the little ekstra code adds up.

> 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.

What you are doing is a perfectly ok use of resources.

regards Max M




More information about the Python-list mailing list