小编Kir*_*aev的帖子

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

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

我的代码:

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)
Run Code Online (Sandbox Code Playgroud)

所以,当我写类似的东西时:

comment_list = Comments()
for comment in comment_list:
    print comment['id']
Run Code Online (Sandbox Code Playgroud)

有用。

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

如何实现呢?

python dictionary class list

2
推荐指数
1
解决办法
104
查看次数

标签 统计

class ×1

dictionary ×1

list ×1

python ×1