Differences between revisions 2 and 3
Revision 2 as of 2003-09-07 17:07:24
Size: 1277
Editor: dsl254-010-130
Comment:
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
Deletions are marked like this. Additions are marked like this.
Line 14: Line 14:
    __slots__ = [] # no attributes
Line 15: Line 16:
        __slots__ = [] # no attributes

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)

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

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