The UserDict Module

The UserDict module contains a dictionary class that can be subclassed (it's actually a Python wrapper for the built-in dictionary type).

Example 2-15 shows an enhanced dictionary class, which allows dictionaries to be "added" to each other and initialized using the keyword argument syntax.

Example 2-15. Using the UserDict Module

File: userdict-example-1.py

import UserDict

class FancyDict(UserDict.UserDict):

 def _ _init_ _(self, data = {}, **kw):
 UserDict.UserDict._ _init_ _(self)
 self.update(data)
 self.update(kw)

 def _ _add_ _(self, other):
 dict = FancyDict(self.data)
 dict.update(b)
 return dict

a = FancyDict(a = 1)
b = FancyDict(b = 2)

print a + b

{'b': 2, 'a': 1}

Core Modules

More Standard Modules

Threads and Processes

Data Representation

File Formats

Mail and News Message Processing

Network Protocols

Internationalization

Multimedia Modules

Data Storage

Tools and Utilities

Platform-Specific Modules

Implementation Support Modules

Other Modules



Python Standard Library
Python Standard Library (Nutshell Handbooks) with
ISBN: 0596000960
EAN: 2147483647
Year: 2000
Pages: 252
Authors: Fredrik Lundh

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net