如何在Python 3中实现UserDict.DictMixin的功能? [英] How to achieve the functionality of UserDict.DictMixin in Python 3?

查看:1857
本文介绍了如何在Python 3中实现UserDict.DictMixin的功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆