找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索本站精品资源

首页 教程频道 查看内容

Python中UserDict、UserString、UserList有用吗?

作者:模板之家 2019-6-4 15:40 11474人关注

Python中UserDict、UserString、UserList都是非常有必要的模块,在C实现的结构的内建方法中会忽略dict的方法。

一个继承Python内建结构的坑儿。从Python 2.2开始,Python支持继承Python内建结构,如list、dict。为了简化项目内容,直接继承了dict,但是结果和预期不一样。现在来好好研究研究:

举个例子:

In : class NewDict(dict):
...:     def __getitem__(self, key):
...:         return 42
...:
In : d = NewDict(a=1)
In : d
Out: {'a': 42}
In : d2 = {}
In : d2.update(d)
In : d2
Out: {'a': 1}

也就是说NewDict的__getitem__方法被dict.update给忽略了。

In : from UserDict import UserDict
In : class NewDict(UserDict):
...:     def __getitem__(self, key):
...:         return 42
...:
In : d = NewDict(a=1)
In : d['b'] =2
In : d
Out: {'a': 1, 'b': 2}
In : d['b']
Out: 42
In : d2 = {}
In : d2.update(d)
In : d2
Out: {'a': 42, 'b': 42}

这才是对的呀。

后来在PyPy的文档中发现了原因,也就是这种C实现的结构的内建方法大部分会忽略重载的那个方法。

之前以为UserDict这样的类是历史遗留问题,现在才知道是有原因的。原来UserDict、UserString、UserList这样的模块是非常必要的。


路过

雷人

握手

鲜花

鸡蛋
来自: Python学习网

全部回复(0)