Revision 1 as of 2003-09-07 17:06:56

Clear message

Subclassing Dictionaries

The process differs by Python version.

Python-2.2

Derive from dict.

ex:

   1 class Msg( dict ):
   2     def __init__( self, msg_type, kv_dict = {} ):
   3         __slots__ = [] # no attributes
   4         dict.__init__( self )
   5         self[ "msg-type" ] = msg_type
   6         self.update( kv_dict )
   7     def Type( self ):
   8         return self[ "msg-type" ]
   9     def __getitem__( self, k ):
  10         return self.get( k, None )
  11     def __delitem__( self, k ):
  12         if self.has_key( k ):
  13             dict.__delitem__( self, k )
  14     def __str__( self ):
  15         pp = pprint.pformat( dict(self) )
  16         return "%s:  %s" % (self.Type(), pp )

The __slots__ line indicates that Msg has no attributes of its own, preserving memory; see UsingSlots.

See Also

["Python-2.2"], SubclassingBuiltInTypes, UsingSlots

Questions

Unable to edit the page? See the FrontPage for instructions.