Differences between revisions 3 and 4
Revision 3 as of 2003-11-05 14:29:31
Size: 1273
Editor: xi
Comment: __slots__ has to be defined at class level; defining it in __init__ doesn't work
Revision 4 as of 2005-01-27 21:07:25
Size: 1343
Editor: out
Comment:
Deletions are marked like this. Additions are marked like this.
Line 40: Line 40:
  [lwickjr]: Before, I think, collected with the other declaritives.

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.

SubclassingDictionaries (last edited 2008-11-15 14:00:59 by localhost)

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