using __setattr__

Mike Fletcher mfletch at tpresence.com
Tue Aug 29 19:15:41 EDT 2000


To set a value in the dictionary of an instance where you have a __setattr__
method, use:
	self.__dict__[ "data" ] = ["     ","        ","       "]

You can then use simple:
	self.data
	self.fields
statements to reference the attribute.  Note: your __getattr__ handler
should explicitly check to see if the key passed is "data" and raise an
attribute error if it is (because there is no attribute of that name in the
dictionary if the __getattr__ hook is called).

Note: for some reason you are doing string formatting both on set and get,
really you should only need one or the other. I'm not really sure why you
want to keep the data as fixed length fields in Python, rather than only
formatting them for fixed length when exporting, but I will leave that you.

Hope this helps,
Mike

-----Original Message-----
From: Jeff Sandys [mailto:sandysj at asme.org]
Sent: Tuesday, August 29, 2000 6:34 PM
To: python-list at python.org
Subject: using __setattr__
...
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, "")
...




More information about the Python-list mailing list