Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/139.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/apache-spark/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 列出类的属性值_Python 3.x - Fatal编程技术网

Python 3.x 列出类的属性值

Python 3.x 列出类的属性值,python-3.x,Python 3.x,如何使用python 3.7动态创建包含类的所有属性值的列表 class Toolchain: VS2008 = 'VS2008' VS2015 = 'VS2015' VS2017 = 'VS2017' VS2017_08 = 'VS2017-08' GCC = 'gcc' CLANG = 'clang' # LIST should contains: ['VS2008', 'VS2015', 'VS2017', 'VS2017-08',

如何使用python 3.7动态创建包含类的所有属性值的列表

class Toolchain:
    VS2008 = 'VS2008'
    VS2015 = 'VS2015'
    VS2017 = 'VS2017'
    VS2017_08 = 'VS2017-08'
    GCC = 'gcc'
    CLANG = 'clang'

    # LIST should contains: ['VS2008', 'VS2015', 'VS2017', 'VS2017-08', 'gcc', 'clang']
我尝试使用列表理解,如下所示:

LIST = [eval(param) for param in dir() if not param.startswith('_')]
但我有一个错误:

NameError: name 'CLANG' is not defined

正如@juanpa.arrivillaga所指出的,您可以通过
\uu dict\uuu
或更可读的
vars()
函数访问类属性。知道它们返回一个字典,您可以使用
items()
来理解列表

LIST = [val for key, val in vars(Toolchain).items() if not key.startswith('_')]
这将为您提供以下输出:

['VS2008', 'VS2015', 'VS2017', 'VS2017-08', 'gcc', 'clang']

vars(Toolchain).values()
但是它也有一些额外的垃圾。请看stdlib。您正在寻找
vars
,它只调用对象的
。\uuuu dict\uuuuu
,在这个类中是一个类,因此您可以获得所有的类属性