Python setattr()找不到明显存在的属性

2024-06-01 01:59:02 发布

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

我束手无策。 找不到其他有帮助的东西。在

dta = {'type': "", 'content': ""}
print dta

>>>{'content': '', 'type': ''}

^{pr2}$

>>>AttributeError: 'dict' object has no attribute 'type'


Tags: noobjecttypeattributecontentdictattributeerrorhas
3条回答

Python的字典不是JS对象。当您创建dict时,您并不是在创建一个动态对象,您可以像JS中那样在运行时更改其属性。相反,字典知道如何存储键和值对,并通过重写运算符[](def __getitem__(self, key))来实现。在

在更高的实现级别上,调用getattr/setattr实际上是data.__getattr__("foo")的缩写,因为dict使用{},而不是{},因此函数调用失败。在

因此,无法使用泛型属性函数设置(或获取)dict的项。在

但是您可以创建支持该操作的自定义dict类(尽管我不建议这样做):

class AttrDict(dict):
    def __init__(self):
        dict.__init__(self)

    # Override getattr and setattr so that they return the values of getitem / setitem
    def __setattr__(self, name, value):
        self[name] = value

    def __getattr__(self, name):
        return self[name]

data = AttrDict()
data["foo"] = "bar"
print(getattr(data, "foo"))

您可以直接分配dict值,不需要setattr()。在

dta = {'type': "", 'content': ""}
dta["type"] = "Steve"

“setattr()”引用其他内容。当您编写setattr(dta, 'type', "Steve")试图访问字段dta.type时,dict类没有属性type,因此它会给出一个错误。在

dict_object['key']是完全不同的事情,它是dict成员应该如何访问的。在

有关settatr()的更多信息Here

相关问题 更多 >