• 技术文章 >Python技术 >Python基础教程

    Python中UserDict、UserString、UserList有用吗?

    PythonPython2019-06-04 15:40:57原创3759
    一个继承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
    品易云
    上一篇:如何在Python中对dicts列表进行排序 下一篇:python几个__开头的方法解释

    相关文章推荐

    • Python使用Pillow添加图片水印• 深究Python中的asyncio库-线程池

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网