gpt4 book ai didi

python - 将标准库中的属性添加到 Python 字典

转载 作者:太空狗 更新时间:2023-10-29 17:25:59 48 4
gpt4 key购买 nike

我想知道是否可以向 Python 字典添加属性?

class myclass():
def __init__():
self.mydict = {} # initialize a regular dict
self.mydict.newattribute = "A description of what this dictionary will hold"
>>> AttributeError: 'dict' object has no attribute 'newattribute'
setattr(self.mydict, "attribute", "A description of what this dictionary will hold"
>>> AttributeError: 'dict' object has no attribute 'newattribute'

有没有办法快速添加我的描述属性,而不必复制 dict 类和重载构造函数。我以为这很简单,但我想我错了。

最佳答案

只需从 dict 派生:

class MyDict(dict):
pass

MyDict 的实例表现得像一个dict,但可以有自定义属性:

>>> d = MyDict()
>>> d.my_attr = "whatever"
>>> d.my_attr
'whatever'

关于python - 将标准库中的属性添加到 Python 字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11532060/

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