Python中UserDict、UserString、UserList有用吗?

404次阅读
没有评论

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

Python中UserDict、UserString、UserList有用吗?

举个例子:

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这样的模块是非常必要的。

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-07-13发表,共计802字。
新手QQ群:570568346,欢迎进群讨论 Python51学习