Python 继承标准类时发生了什么

定义标准类dict的一个子类c:

>>> class c(dict):
pass >>> y=c({1:2,3:4})
>>> y
{1: 2, 3: 4}
>>> y.__dict__
{}
>>> z={1:2,3:4}
>>> z.__dict__
Traceback (most recent call last):
File "<pyshell#98>", line 1, in <module>
z.__dict__
AttributeError: 'dict' object has no attribute '__dict__'
>>> dir(y)
['__class__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
>>> dir({})
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
>>> set(dir(y))-set(dir({}))
{'__module__', '__weakref__', '__dict__'}

可见,子类反而比父类多了3个属性:

{'__module__', '__weakref__', '__dict__'}

暂时不知有何深意.

上一篇:ibatis入门教程


下一篇:IPD模式下开展敏捷开发的一些问题汇总