gpt4 book ai didi

python - 通过类属性访问的字典列表

转载 作者:行者123 更新时间:2023-11-28 21:46:30 31 4
gpt4 key购买 nike

我有一个字典列表,我需要访问字典值作为属性。

我的代码:

class Comments:

def __init__(self):
self.comments = [{'id': 1, 'title': 'bla'},
{'id': 2, 'title': 'bla2'},
{'id': 3, 'title': 'bla3'}]

def __iter__(self):
return iter(self.comments)

所以,当我写这样的东西时:

comment_list = Comments()
for comment in comment_list:
print comment['id']

有效。

但我想使用属性作为 comment.id 而不是 comment['id']

如何实现?

最佳答案

正如@Tim Castelijns 所说,dict 不是这样工作的。

您寻求的行为可以通过拥有一个包含 idtitle 作为成员的 Comment 类来实现。

class Comment

def __init__(self, id, title):
self.id = id
self.title = title

class CommentsHolder:

def __init__(self):
self.comments = [Comment(1,'bla'),
Comment(2,'bla2'),
Comment(3, 'bla3')]

def __iter__(self):
return iter(self.comments)

然后你可以这样做:

for comment in CommentsHolder():
print(comment.id)

此外,您可以查看 Bunch module , 这是一个点访问字典。但是,如果您使用的是 python 3,请注意它可能无法正常工作。 (至少它不适合我。)

关于python - 通过类属性访问的字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37834417/

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