什么是使用了UserDict类的优势是什么?
我的意思是,我真正得到,如果代替
class MyClass(object):
def __init__(self):
self.a = 0
self.b = 0
...
m = MyClass()
m.a = 5
m.b = 7
我会写:
class MyClass(UserDict):
def __init__(self):
UserDict.__init__(self)
self["a"] = 0
self["b"] = 0
...
m = MyClass()
m["a"] = 5
m["b"] = 7
编辑 :如果我理解正确的,我可以在这两种情况下运行时新字段添加到一个对象?
m.c = "Cool"
和
m["c"] = "Cool"
UserDict.UserDict
has no substantial added value since Python 2.2, since, as @gs mention, you can now subclass dict
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 the collections
module) since, as the docs now mention,
The need for this class has been
partially supplanted by the ability to
subclass directly from dict; however,
this class can be easier to work with
because the underlying dictionary is
accessible as an attribute.
UserDict.DictMixin
, in Python 2, is quite handy -- as the docs say,
The module defines a mixin, DictMixin,
defining all dictionary methods for
classes that already have a minimum
mapping interface. This greatly
simplifies writing classes that need
to be substitutable for dictionaries
(such as the shelve module).
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; also keys
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 of dict
'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 on collections.MutableMapping
instead (or just collections.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).
子类的字典给你一个字典的所有功能,如if x in dict:
。 如果你想扩展字典的功能,创建例如有序字典通常你做到这一点。
BTW:在最近的Python版本,那么可以继承dict
直接,你不需要UserDict
。