在“fluent\u python”的继承一章中,它演示了一个替代重写内置类型的示例
In [50]: class AnswerDict2(collections.UserDict):
...: def __getitem__(self, key):
...: return 42
...:
它能很好地发挥作者的意图
In [60]: ad = AnswerDict2(a="foo")
In [61]: ad["a"]
Out[61]: 42
In [62]: d = {}
In [63]: d.update(ad)
In [64]: d
Out[64]: {'a': 42}
然而,广告的原稿仍然没有被改写:
In [65]: ad
Out[65]: {'a': 'foo'}
怎么可能:
In [65]: ad
Out[65]: {'a': 42}
您可以替代
__init__
方法:以便:
将输出:
相关问题 更多 >
编程相关推荐