码迷,mamicode.com
首页 > 编程语言 > 详细

【Python】【继承】

时间:2017-10-20 20:15:20      阅读:241      评论:0      收藏:0      [点我收藏+]

标签:c 语言   object   其他   sel   value   tab   item   get   自定义   

#栗子12-1 内置类型dict 的__init__和__update__方法会忽略我们覆盖的__setitem__

class DoppelDict(dict):
def __setitem__(self, key, value):
super().__setitem__(key,[value]*2)
dd = DoppelDict(one=1)
print(dd) #{‘one‘: 1}
dd[‘two‘] = 2
print(dd) #{‘one‘: 1, ‘two‘: [2, 2]}
dd.update(three=3)
print(dd) #{‘one‘: 1, ‘two‘: [2, 2], ‘three‘: 3}


#不只实例内部的调用有这个问题(self.get() 不调用 self.__getitem__()),内置类型的方法调用的其他类的方法,如果被覆盖了,也不会被调用

#栗子12-2 dict.update方法会忽略AnswerDict.__getitem__方法
class AnswerDict(dict):
def __getitem__(self, item):
return 42
ad = AnswerDict(a=‘foo‘)
print(ad[‘a‘]) #42
d = {}
d.update(ad)
print(d[‘a‘]) #foo
print(d) #{‘a‘: ‘foo‘}


import collections

class DoppelDict2(collections.UserDict):
def __setitem__(self, key, value):
super().__setitem__(key,[value]*2)
dd = DoppelDict2(one=1)
print(dd) #{‘one‘: [1, 1]}
dd[‘two‘] = 2
print(dd) #{‘one‘: [1, 1], ‘two‘: [2, 2]}
dd.update(three=3)
print(dd) #{‘one‘: [1, 1], ‘two‘: [2, 2], ‘three‘: [3, 3]}
class AnswerDict2(collections.UserDict):
def __getitem__(self, item):
return 42
ad = AnswerDict2(a=‘foo‘)
print(ad[‘a‘]) #42
d = {}
d.update(ad)
print(d[‘a‘]) #42
print(d) #{‘a‘: 42}





#【小结】
‘‘‘
综上,本节所述的问题只发生在 C 语言实现的内置类型内部的方法委托上,而且只影响
直接继承内置类型的用户自定义类。如果子类化使用 Python 编写的类(collections 模块),如 UserDict 或
MutableMapping,就不会受此影响
‘‘‘


#12.2 多重继承和方法解析顺序
#规则:按照__mro__(方法解析)顺序,若直接用类名调用方法则直接找到该类,建议使用super()[因为最安全,也不容易过时。]
print(bool.__mro__) #(<class ‘bool‘>, <class ‘int‘>, <class ‘object‘>)

【Python】【继承】

标签:c 语言   object   其他   sel   value   tab   item   get   自定义   

原文地址:http://www.cnblogs.com/suren2017/p/7700736.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!