【问题标题】:The reason for not able to access my object item无法访问我的对象项目的原因
【发布时间】:2019-08-30 12:29:34
【问题描述】:

我正在创建一个类并设置一些属性。我将字典作为类对象引用。但无法访问对象的第二个元素。

我试图用谷歌搜索这个问题,但它没有说明问题的原因。

data = {
'a': {
'vsdf': 'asfas',
'nfgn': 'aser',
'aser': 'rtydf'
},
'b': ['ndfg', 'ndf', 'safd']
}

My class looks something like this:
    def __init__(self, meta):
        self.meta = meta

and when i create the object of this class like this:

request = Request(data)

and try to print the request['b'] it shows the error "'Request' object is not subscriptable" 

实际结果应该是这样的: ['', '', '']

但它显示: “请求”对象不可下标

【问题讨论】:

    标签: python-3.x class object


    【解决方案1】:

    使用您提供的代码,data 字典将存储在 meta 实例变量中。您需要首先访问该变量来访问它,即request.meta['b']

    为了让它按照你想要的方式运行,你需要遍历传入__init__ 的字典并单独设置每个变量。看看这个答案如何做到这一点:Set attributes from dictionary in python

    【讨论】:

    • 是的,我做到了,它成功了,但我没有得到原因?
    • 基本上,python 对象属性不是字典,就像它们在 perl 中那样(即使在幕后它们被实现为字典)。您不能在一次操作中批量设置它们。据我所知,self.meta 在 python 中没有特殊含义,因此您只是将对象上名为“meta”的属性设置为您传入的“data”字典的副本。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-12
    • 2012-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多