简体   繁体   English

如何从python类中的实例变量获取所有值的列表

[英]How to get a list of all values from instance variables in a python class

I have a class that looks like this: 我有一堂课,看起来像这样:

class HTTP_HEADERS:
    ACCEPT = "X-Accept"
    DECLINE = "X-Decline"

To get all the variable names out of the class I can do something along the lines of: 为了从类中获取所有变量名,我可以执行以下操作:

members = [
        attr for attr in dir(HTTP_HEADER)
        if not callable(getattr(HTTP_HEADER, attr))
        and not attr.startswith("__")
    ]

This will return a list of variable names, like so: 这将返回变量名列表,如下所示:

["ACCEPT", "DECLINE"]

Now what I want to do, is get the values of those variables into a list. 现在,我要做的就是将这些变量的值放入列表中。 For example the output should be: 例如,输出应为:

["X-Accept", "X-Decline"]

How can I do this successfully? 我该如何成功完成?

If you have this: 如果您有这个:

class HTTP_HEADER:
    ACCEPT = "X-Accept"
    DECLINE = "X-Decline"

names = ["ACCEPT", "DECLINE"]

Getting the values is simply a matter of 获得价值只是一个问题

values = [getattr(HTTP_HEADER, name) for name in names]

I think a dictionary is more appropriate though, and it can be done with minimal change to your original code: 我认为字典更合适,并且只需对原始代码进行最小的更改即可完成:

members = {
        k: v for k, v in vars(HTTP_HEADER).items()
        if not callable(v)
        and not k.startswith("__")
    }

which gives 这使

{'ACCEPT': 'X-Accept', 'DECLINE': 'X-Decline'}

You should define this as an Enum . 您应该将其定义为Enum

class HTTP_HEADERS(enum.Enum):
    ACCEPT = "X-Accept"
    DECLINE = "X-Decline"

Now you can simply do: 现在,您可以简单地执行以下操作:

[x.value for x in HTTP_HEADERS]

Use getattr again to access class variable 再次使用getattr访问类变量

[getattr(HTTP_HEADERS,m) for m in members]

Output 产量

['X-Accept', 'X-Decline']

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

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