a problem with subclassing a dict
Fernando Pérez
fperez528 at yahoo.com
Sat Apr 6 21:53:30 EST 2002
Rajarshi Guha wrote:
> Hi,
> I was playing with some code from a tutorial by GvR
> (http://www.python.org/2.2/descrintro.html) - the relevant code is:
>
> class mydict(dict):
>
> def __init__(self, default=None):
> dict.__init__(self)
> self.default = default
>
> def __getitem__(self, key):
> try:
> return dict.__getitem__(self, key)
> except KeyError:
> return self.default
>
> md = mydict("Sorry - no such key!!")
> md = {1:2}
>
> print md[1]
> print md[2]
> ---------------------------------
>
> I get:
>
> 2
> Traceback (most recent call last):
> File "p2.py", line 22, in ?
> print md[2]
> KeyError: 2
>
>
> Should'nt I be seeing a message instead of the Traceback?
The problem is simply that your second statement (md={1:2}) wiped out the
assignment of md and now md is a regular dict:
In [17]: md = mydict("Sorry - no such key!!")
In [18]: md[1]
Out[18]: 'Sorry - no such key!!'
In [19]: type md
-------> type (md)
Out[19]: <class '__main__.mydict'>
In [20]: md = {1:2}
In [21]: type md
-------> type (md)
Out[21]: <type 'dict'>
In [22]: md[1]
Out[22]: 2
In [23]: md[2]
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
?
KeyError: 2
So, it's not a problem with the new classes. You simply assigned md to a
normal dict, you can't expect it then to behave like a mydict, can you?
Cheers,
f.
More information about the Python-list
mailing list