Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/313.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中获取类中的所有常量_Python_Class_Python 2.7_Constants - Fatal编程技术网

在python中获取类中的所有常量

在python中获取类中的所有常量,python,class,python-2.7,constants,Python,Class,Python 2.7,Constants,我有一个类,它基本上用于为其他类定义公共常量。它看起来如下所示: class CommonNames(object): C1 = 'c1' C2 = 'c2' C3 = 'c3' 我想“pythonically”得到所有的常量值。如果我使用了CommonNames.\uu dict\uuu.values()我会得到那些值('c1',等等),但我会得到其他东西,比如: <attribute '__dict__' of 'CommonNames' objects>

我有一个类,它基本上用于为其他类定义公共常量。它看起来如下所示:

class CommonNames(object):
    C1 = 'c1'
    C2 = 'c2'
    C3 = 'c3'
我想“pythonically”得到所有的常量值。如果我使用了
CommonNames.\uu dict\uuu.values()
我会得到那些值(
'c1'
,等等),但我会得到其他东西,比如:

<attribute '__dict__' of 'CommonNames' objects>,
<attribute '__weakref__' of 'CommonNames' objects>,
None ...
,
,
没有一个
这是我不想要的


我希望能够获取所有值,因为此代码稍后将被更改,我希望其他地方了解这些更改。

您必须通过筛选名称来明确筛选出这些值:

[value for name, value in vars(CommonNames).iteritems() if not name.startswith('_')]
这将为任何不以下划线开头的名称生成一个值列表:

>>> class CommonNames(object):
...     C1 = 'c1'
...     C2 = 'c2'
...     C3 = 'c3'
... 
>>> [value for name, value in vars(CommonNames).iteritems() if not name.startswith('_')]
['c3', 'c2', 'c1']
对于这样的枚举,最好使用添加到Python 3.4中的新枚举:

from enum import Enum

class CommonNames(Enum):
    C1 = 'c1'
    C2 = 'c2'
    C3 = 'c3'

values = [e.value for e in CommonNames]

如果您试图在python3中使用Martijn示例,那么应该使用items()而不是iteritmes(),因为它已被弃用

[名称的值,变量中的值(CommonNames).items()如果不是name.startswith(“”“)]