using __setattr__

Jeff Sandys sandysj at asme.org
Tue Aug 29 18:34:04 EDT 2000


I am writing a little data converter to format data for a mainframe 
application.  Each data item needs to be a fixed field length.  This 
data converter will probably be maintained by the even less experienced 
users than myself, therefore I wanted the to make the data assignments 
as readable a possible, e.i.:

x.data_item_one = 'this_data'
x.data_item_two = 'that_data'

In order to do this I need to write a __setattr__ and __getattr__ method.
The problem is that these methods suck up ALL the instance attributes and 
make it impossible to access self.data (as in the example below).  I can 
get the proper behavior by using data instead of self.data but then each 
instance shares the same data.

Can anyone help?
Thanks,
Jeff Sandys


class special:
    fields = {'curly':(0,5),
              'moe':(1,8),
              'larry':(2,7)}
    def __init__(self):
        self.data = ["     ","        ","       "]
    def __setattr__(self, item, value):
        if special.fields.has_key(item):
            (pos, leng) = special.fields[item]
            self.data[pos] = "%-*.*s" % (leng, leng, value)
    def __getattr__(self, item):
        if special.fields.has_key(item):
            (pos, leng) = special.fields[item]
            return "%-*.*s" % (leng, leng, self.data[pos])
    def record(self):
        return string.join(self.data, "")
#
# desired behavior
# to assign fields of fixed length and
# print the records for a main-frame.
#
#>>> x = special()
#>>> x.curly = "too-long"
#>>> x.curly
# 'too-l'                  # curly is limited to 5 chars
#>>> x.moe = "short"
#>>> x.moe
# 'short   '               # moe must be 8 chars long
#>>> x.larry = x.moe
#>>> x.record()
# 'too-lshort   short  '
#>>> y = special()
#>>> y.moe = 'funny'
#>>> y.moe
# 'funny   '
#>>> x.moe
# 'short   '               # each instance needs to be separate



More information about the Python-list mailing list