重写内置类型方法

2024-09-29 22:18:55 发布

您现在位置:Python中文网/ 问答频道 /正文

在“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}

Tags: inself示例类型foodefoutfluent
1条回答
网友
1楼 · 发布于 2024-09-29 22:18:55

您可以替代__init__方法:

import collections
class AnswerDict2(collections.UserDict):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        for key in kwargs:
            self[key] = 42

以便:

ad = AnswerDict2(a="foo")
print(ad)

将输出:

{'a': 42}

相关问题 更多 >

    热门问题