a problem with subclassing a dict

Rajarshi Guha rxg218 at psu.edu
Sat Apr 6 08:35:59 EST 2002


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?

My python is compiled  on a RH 7.2 system, with GCC 3.0 - 

Python 2.2.1c2 (#1, Apr  6 2002, 07:51:35) 
[GCC 3.0.2 20010905 (Red Hat Linux 7.1 3.0.1-3)]linux2

Any suggestions would be appreciated.
TIA,


-------------------------------------------------------------------
Rajarshi Guha                  | email: rajarshi at presidency.com
417 Davey Laboratory           | web  : http://jijo.cjb.net
Department of Chemistry        | ICQ  : 123242928
Pennsylvania State University  | AIM  : LoverOfPanda
-------------------------------------------------------------------
GPG Fingerprint: DCCB 4D1A 5A8B 2F5A B5F6  1F9E CDC4 5574 9017 AF2A 
Public Key     : http://pgp.mit.edu/
-------------------------------------------------------------------
A meeting is an event at which the minutes are kept and the hours are lost.




More information about the Python-list mailing list