简体   繁体   English

将类中所有实例变量转换为列表的快速方法(Python)

[英]Quick way to convert all instance variables in a class, to a list (Python)

I have created a class with around 100+ instance variables (as it will be used in a function to do something else). 我创建了一个带有约100多个实例变量的类(因为它将在函数中用于执行其他操作)。

Is there a way to translate all the instance variables; 有没有办法翻译所有实例变量? into an array list. 进入数组列表。 Without manually appending each instance variable. 无需手动附加每个实例变量。

For instance: 例如:

class CreateHouse(object):
    self.name = "Foobar"
    self.title = "FooBarTest"
    self.value = "FooBarValue"
    # ...
    # ...
    # (100 more instance variables) 

Is there a quicker way to append all these items to a list: Quicker than: 有没有一种更快的方法将所有这些项目附加到列表中?

theList = []

theList.append(self.name)
theList.append(self.title)
theList.append(self.value)
# ... (x100 elements)

The list would be used to perform another task, in another class/method. 该列表将用于执行另一个类/方法中的另一个任务。

The only solution (without totally rethinking your whole design - which FWIW might be an option to consider, cf my comments on your question) is to have a list of the attribute names (in the order you want them in the final list) and use getattr 唯一的解决方案(无需完全重新考虑您的整个设计-可以考虑使用FWIW,请参阅我对您的问题的评论)是具有属性名称的列表(以您希望它们在最终列表中的顺序)并使用getattr

class MonstruousGodClass(object):
    _fields_list = ["name", "title", "value", ] #etc...

    def as_list(self):
        return [getattr(self, fieldname) for fieldname in self._fields_list]

Now since, as I mentionned in a comment, a list is NOT the right datatype here (from a semantical POV at least), you may want to use a dict instead - which makes the code much simpler: 现在,正如我在评论中提到的那样,这里的list不是正确的数据类型(至少从语义POV),因此您可能想使用dict ,这使代码更加简单:

    import copy 

    def as_dict(self):
        # we return a deepcopy to avoid unexpected side-effects
        return copy.deepcopy(self.__dict__) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM