子类化内置类型

python2.2之后,内置类型都可以子类化,但是有一个注意事项:内置类型不会调用用户定义的类覆盖的特殊方法。这个说起来比较绕口,什么意思呢。我们来看下下面的代码:

class DopperDict(dict):
def __setitem__(self, key, value):
super(DopperDict,self).__setitem__(key,[value]*2) ⑴


if __name__=="__main__":
dd=DopperDict(one=1) ⑵
print dd
dd['two']=2 ⑶
print dd
dd.update(three=3) ⑷
print dd

E:\python2.7.11\python.exe E:/py_prj/fluent_python/chapter12.py

{'one': 1}

{'two': [2, 2], 'one': 1}

{'three': 3, 'two': [2, 2], 'one': 1}

1中,重写了__setitem__方法,并委托超类进行赋值

2中,继承自dict的__init__忽略了被覆盖的__setitem__方法,one值并没有重复

3 中,[]运算符会调用我们覆盖的__setitem__方法,按照预期工作。Two对应的是两个重复的值。

4中,继承自dict的update方法也不使用我们覆盖的__setitem__方法,three的值没有重复。

这就会导致初始化和赋值的时候得到的结果不一样,那么如何解决呢:

可以使用collections.UserDict模块。

class AnswerDict(dict):
def __getitem__(self, item):
return 42

class DopperDict(collections.UserDict):
def __setitem__(self, key, value):
super(DopperDict,self).__setitem__(key,[value]*2)

在这种情况下,初始化调用覆盖的__setitem__方法。

本章还介绍了关于多重继承的方法。这个在之前的一篇帖子中介绍过。请参考:http://www.cnblogs.com/zhanghongfeng/p/7190732.html

更多相关文章

  1. Python 字典 pop() 方法
  2. 对照java和spring理解python中单例模式的装饰器方法
  3. Python下numpy不成功的解决办法(wheel方法安装,试用其他包)
  4. 关于python中的类方法(classmethod)和静态方法(staticmethod)
  5. python中的类与方法
  6. 如何为Google Cloud Endpoints方法生成pydoc文档?
  7. python笔记7:接口实现方法
  8. 用于搜索和替换大字符串的最快Python方法
  9. 【Python】Python3 字典 copy()方法

随机推荐

  1. 在centos7中python3的安装注意
  2. Python3.6中PyInstaller不能对文件进行打
  3. 【实例】python re 正则表达式 同时选择
  4. 用积分来解拟合方程。
  5. The bytes/str dichotomy in Python 3
  6. python实现单例模式
  7. 自学Python七 爬虫实战一
  8. Python文件遍历的三种方法
  9. 信息隐藏-空域隐藏-python-LSB
  10. Django EventLog:传入当前用户