How can I use __setitem__ method of dict object?

jeremito jeremit0 at gmail.com
Tue Feb 6 10:23:08 EST 2007


Please excuse me if this is obvious to others, but I can't figure it
out.  I am subclassing dict, but want to prevent direct changing of
some key/value pairs.  For this I thought I should override the
__setitem__ method as such:


class xs(dict):
    """
    XS is a container object to hold information about cross sections.
    """

    def __new__(cls, xS=1.0, xF=1.0, xG=1.0, nu=1.0, debug=0):
        """
        """
        x = {}
        x['xS'] = xS
        x['xF'] = xF
        x['nu'] = nu
        x['xG'] = xG
        x['xA'] = x['xG'] + x['xF']
        x['xT'] = x['xA'] + x['xS']

        return x

    def __setitem__(self, key, value):
        """
        I have overridden this method to prevent setting xT or xA
outside the
        class.
        """
        print "I am in __setitem__"
        if key == 'xT':
            raise AttributeError("""Can't change xT.  Please change,
xF, xS, or xG""")


But I can't even get __setitem__ to run.  Example:
Python 2.5 (r25:51918, Sep 19 2006, 08:49:13)
[GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import xs
>>> cs = xs.xs()
>>> cs
{'xA': 2.0, 'xF': 1.0, 'xG': 1.0, 'xS': 1.0, 'nu': 1.0, 'xT': 3.0}
>>> cs['xT'] = 3.1415
>>> cs
{'xA': 2.0, 'xF': 1.0, 'xG': 1.0, 'xS': 1.0, 'nu': 1.0, 'xT':
3.1415000000000002}


Is this what the __setitem__ method is for?  If not, how can I do what
I want to do?
Thanks in advance,
Jeremy




More information about the Python-list mailing list