问题描述
在Python 3中, UserDict.DictMixin
类被移动到集合
模块。该文档建议在其位置使用 collections.MutableMapping
,但是这个抽象类不提供许多方法, DictMixin
do / did。
In Python 3 the UserDict.DictMixin
class was moved to the collections
module. The docs suggest using collections.MutableMapping
in its place, however this abstract class does not provide a number of the methods that the DictMixin
does/did.
是否有另一种(或更好)的方式来定义它们,而不是抓取 UserDict.Mixin的私人副本
来源(或者只是将需要的部分)复制到我自己的字典类中?
Is there another (or better) way to define them short of grabbing a private copy of the UserDict.Mixin
source for importing (or perhaps just copying the needed portions of) it into my own dictionary-like class?
推荐答案
方法的数量特别是 __ len __
和 __ iter __
,所以额外的工作不是那么多。
The "number of methods" are specifically __len__
and __iter__
so the additional work is not that much.
def __len__(self):
return len(self.mylist)
def __iter__(self):
for i in self.mylist:
yield i
应该工作,我想(未经测试,但是)。
Should work, I think (untested, though).
这篇关于如何在Python 3中实现UserDict.DictMixin的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!