gpt4 book ai didi

python - UserDict 类的优点?

转载 作者:IT老高 更新时间:2023-10-28 21:16:00 26 4
gpt4 key购买 nike

使用 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自 Python 2.2 以来没有实质性的附加值,因为正如@gs 所提到的,您现在可以直接继承 dict ——它的存在只是为了向后兼容 Python 2.1 及更早版本,当内置类型不能是子类时.尽管如此,它仍然保存在 Python 3 中(现在在 collections 模块中的适当位置),因为 the docs现在提一下,

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,在 Python 2 中,非常方便——正如文档所说,

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).

您将其子类化,定义一些基本方法(至少 __getitem__,这对于无法获取键或迭代的只读映射就足够了;还有 keys如果您需要这些功能;可能是 __setitem__,并且您有一个 R/W 映射,但无法删除项目;添加 __delitem__ 以获得完整功能,并可能覆盖其他方法性能原因),并获得 dict 的丰富 API(updateget 等)的完整实现。 Template Method 的一个很好的例子设计模式。

在 Python 3 中,DictMixin 消失了;您可以几乎通过依赖 collections.MutableMapping 来获得相同的功能(或者只是 collections.Mapping 用于 R/O 映射)。它更优雅一些,虽然不是很方便(见 this issue ,以“不会修复”结束;简短的讨论值得一读)。

关于python - UserDict 类的优点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1392396/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com