classes for fun and newbies

Bengt Richter bokr at oz.net
Wed Mar 20 13:55:10 EST 2002


On Wed, 20 Mar 2002 06:26:54 -0500, "Bruce Dykes" <bkd at graphnet.com> wrote:

>Just to make sure I'm on the right track here...
>
>I'm reading records from a file. This is a flat file, with one line per
>record, and each line being some 380+ characters long, with about 40 fields
>in each record.
>
>Now I'm thinking that the easiest way to deal with these records (in
>preparation for developing a Zope app to interface with them), is to set up
>a class, with attributes for each field:
>
>class call_record:
>    def __init__(self, record=''):
>        self.record_id=record[0:5]
>        self.date=record[6:11]
>
>etc...
>
>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])
>
You probably want
    apro = call_record(log[1]) #apro: a_parsed_record_object
and then
    print apro.record_id

but you might also give your objects a __str__ function to make
a default printing string, e.g.,
    def __str__(self):
        return '<This is a call_record with record_id "%s">' % self.record_id
then
    print apro

will print whatever __str__ returned.

You could also return formatted strings for different standard views that
you might want to print, with statments like

    print apro.brief_view()
or
    print apro.full_view()
or even
    print apro.formatted_view('a string to control formatting')

Once you have decided to make objects, you have the opportunity to
give them behaviors (methods) too, not just attributes to access.
This can clean up the code that uses the objects.

>However, all I get when I try this is the return of of the object attribute
>instance and its memory address.
>
You know why by now.

>Am I on the right track and just overlooking something obvious? Is there
>already an app that does something similar that I can browse for pointers?
>
>On a side note, it was fun just cranking out a python script that created
>the class code from the file documentation. 8-)
>
Python is cool in many ways ;-)

HTH
Regards,
Bengt Richter




More information about the Python-list mailing list