How can I use __setitem__ method of dict object?
Steve Holden
steve at holdenweb.com
Tue Feb 6 10:53:15 EST 2007
jeremito wrote:
> 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?
>>> class d(dict):
... def __setitem__(self, k, v):
... print "Setting", k
... dict.__setitem__(self, k, v)
...
>>> dd = d()
>>> dd['steve'] = 'holden'
Setting steve
>>> dd['steve']
'holden'
>>>
I believe the problem is that your __new__ method does not return an
object of type xs but a dict, so it does not inherit the __getitem__
method from xs but instead from dict.
regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Blog of Note: http://holdenweb.blogspot.com
See you at PyCon? http://us.pycon.org/TX2007
More information about the Python-list
mailing list