Subclassing Dictionaries
The process differs by Python version.
Python-2.2
Derive from dict.
ex:
1 class Msg( dict ):
2 __slots__ = [] # no attributes
3 def __init__( self, msg_type, kv_dict = {} ):
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
Is this bad Python-2.2 code? Make improvements..! I do think it's worth showing how to use slots in the context of subclassing dict; In many cases, I think, people would want to do it. I do wonder if slots should be specified before or after the initializer- something to put on the UsingSlots page. -- LionKimbro DateTime(2003-09-07T17:07:24Z) [lwickjr]: Before, I think, collected with the other declaritives.