【发布时间】:2016-10-16 12:12:15
【问题描述】:
我有一个字典列表,我需要访问字典值作为属性。
我的代码:
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']。
如何实现?
【问题讨论】:
-
你为什么想要那个?这不是 dicts 的工作方式。它会使阅读您的代码的人感到困惑
-
你会使用setattr()。
标签: python list class dictionary