Differences between revisions 1 and 2
Revision 1 as of 2003-09-07 17:06:56
Size: 1228
Editor: dsl254-010-130
Comment:
Revision 2 as of 2003-09-07 17:07:24
Size: 1277
Editor: dsl254-010-130
Comment:
Deletions are marked like this. Additions are marked like this.
Line 39: Line 39:
  * 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.   * 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)]]

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

  • 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.