What are advantages of using UserDict class?
I mean, what I really get if instead of
class MyClass(object):
def __init__(self):
self.a = 0
self.b = 0
...
m = MyClass()
m.a = 5
m.b = 7
I will write the following:
class MyClass(UserDict):
def __init__(self):
UserDict.__init__(self)
self["a"] = 0
self["b"] = 0
...
m = MyClass()
m["a"] = 5
m["b"] = 7
Edit: If I understand right I can add new fields to an object in a runtime in both cases?
m.c = "Cool"
and
m["c"] = "Cool"
Subclassing the dict gives you all the features of a dict, like
if x in dict:
. You normally do this if you want to extend the features of the dict, creating an ordered dict for example.BTW: In more recent Python versions you can subclass
dict
directly, you don't needUserDict
.UserDict.UserDict
has no substantial added value since Python 2.2, since, as @gs mention, you can now subclassdict
directly -- it exists only for backwards compatibility with Python 2.1 and earlier, when builtin types could not be subclasses. Still, it was kept in Python 3 (now in its proper place in thecollections
module) since, as the docs now mention,UserDict.DictMixin
, in Python 2, is quite handy -- as the docs say,You subclass it, define some fundamental methods (at least
__getitem__
, which is sufficient for a read-only mapping without the ability to get keys or iterate; alsokeys
if you need those abilities; possibly__setitem__
, and you have a R/W mapping without the ability of removing items; add__delitem__
for full capability, and possibly override other methods for reasons of performance), and get a full-fledged implementation ofdict
's rich API (update
,get
, and so on). A great example of the Template Method design pattern.In Python 3,
DictMixin
is gone; you can get almost the same functionality by relying oncollections.MutableMapping
instead (or justcollections.Mapping
for R/O mappings). It's a bit more elegant, though not QUITE as handy (see this issue, which was closed with "won't fix"; the short discussion is worth reading).