【问题标题】:Iterate over object properties and change them?迭代对象属性并更改它们?
【发布时间】:2012-02-25 03:17:19
【问题描述】:

有没有办法做我想做的事情:

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]

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

【问题讨论】:

    标签: python properties


    【解决方案1】:

    遍历名称;那么你可以使用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])
    

    【讨论】:

    • 比 DSM 的回答稍微复杂一点,但还是谢谢你。教育。
    • @mlissner 这是更通用的解决方案,因为它不依赖于列表中的项目。
    【解决方案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']}
    

    【讨论】:

    • 有时我很喜欢。感谢您在我当前的代码中添加 [:] 后提供的快速、详细和出色的答案。你能解释一下这是做什么的吗?没见过?
    • [:] 表示没有指定开始或结束的切片,这意味着它需要整个内容。 a_list[:] 制作列表的浅表副本。当分配给那个切片时,意味着你移除了指定的切片并用给定的列表替换它,所以a_list[:] = b_list将给a_listb_list的所有内容,同时仍然保持a_list的对象标识(这就是为什么你不需要 setattr 这样)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-28
    • 2023-03-24
    • 2013-09-29
    • 1970-01-01
    相关资源
    最近更新 更多