classes for fun and newbies

Kragen Sitaker kragen at pobox.com
Wed Mar 20 18:37:37 EST 2002


"Bruce Dykes" <bkd at graphnet.com> writes:
> class call_record:
>     def __init__(self, record=''):
>         self.record_id=record[0:5]
>         self.date=record[6:11]

I'd use:

import struct
self.record_id, self.date = struct.unpack("5s x 5s", record)

This has the following advantages:
- it makes it clear that you're skipping a byte between record_id and date
  (after you read struct.__doc__ to find out what x means)
- it doesn't require math to figure out the length of each field
- it gives you an error instead of silently wrong results if the
  format string is wrong (although the error is not very helpful)
- it's a lot shorter

It has the disadvantage that errors are harder to diagnose --- you
have to use struct.calcsize to figure out whether your string is too
long or too short, then change the string or the format to get it to
work, then look at the results.




More information about the Python-list mailing list