gpt4 book ai didi

python - 我应该如何理解python中的 "Bunch class"?

转载 作者:太空宇宙 更新时间:2023-11-04 09:01:32 26 4
gpt4 key购买 nike

今天学习了《Python算法》这本书上的一个Bunch类

class Bunch(dict):
def __init__(self, *args, **kwds):
super(Bunch, self).__init__(*args, **kwds)
self.__dict__ = self

但是我不太明白第三行是做什么的:

super(Bunch, self).__init__(*args, **kwds)

我知道它会调用父类,并做类似的事情:

dict.__init__(self, *args, **kwds)

但我不知道 __init__ 函数对字典做了什么。

我该如何理解?

最佳答案

您可以将 dict.__init__ 视为字典构造函数。例如我可以写:

d = dict(a=1, b=2)

d = dict([('a', 1), ('b', 2)])

两者都创建(初始化)字典 {'a': 1, 'b': 2}。每当我写这两个语句时,它都会调用 dict.__init__ 来完成添加 ab 项目的工作。

以同样的方式,对于 Bunch,它会导致所有关键字参数(或 2-sequences 的可迭代对象)在字典子类(一堆).

关于python - 我应该如何理解python中的 "Bunch class"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24902969/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com