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}
Категории