迭代对象属性并更改它们?

时间:2012-02-25 03:17:20

标签: python properties

有没有办法做我想在这里做的事情:

for item in [self.docket_numbers, self.neutral_citations,
             self.lower_courts, self.lower_court_judges,
             self.dispositions, self.judges, self.nature_of_suit]:
    if item is not None:
        item = [clean_string(sub_item) for sub_item in item]

显然,在最后一行中,我需要将列表解释的结果分配给对象......但我不确定如何。

2 个答案:

答案 0 :(得分:3)

迭代名字;然后您可以使用getattrsetattr

for attr in ('docket_numbers', 'neutral_citations',
             'lower_courts', 'lower_court_judges',
             'dispositions', 'judges', 'nature_of_suit'):
    item = getattr(self, attr)
    if item is not None:
        setattr(self, attr, [clean_string(sub_item) for sub_item in item])

答案 1 :(得分:2)

如果各种项目都是列表,它们看起来很像,你不需要setattr,你可以简单地就地更改它们:

>>> def clean_string(s):
...     return ''.join(c for c in s if c != '7')
... 
>>> class Court(object):
...     def __init__(self):
...         self.docket_numbers = ["a1", "b277"]
...         self.dispositions = ["happy", "sad77"]
...     def clean(self):
...         for item in [self.docket_numbers, self.dispositions]:
...             if item is not None:
...                 item[:] = [clean_string(sub_item) for sub_item in item]
... 
>>> C = Court()
>>> vars(C)
{'dispositions': ['happy', 'sad77'], 'docket_numbers': ['a1', 'b277']}
>>> C.clean()
>>> vars(C)
{'dispositions': ['happy', 'sad'], 'docket_numbers': ['a1', 'b2']}