This is a static archive of the Python wiki, which was retired in February 2026 due to lack of usage and the resources necessary to serve it — predominately to bots, crawlers, and LLM companies.
Pages are preserved as they were at the time of archival. For current information, please visit python.org.
If a change to this archive is absolutely needed, requests can be made via the infrastructure@python.org mailing list.

Subclassing Dictionaries

The process differs by Python version.

Python-2.2

Derive from dict.

ex:

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


2026-02-14 16:13