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

Getting all constants within a class in python

我有一个class,它本质上是用来为其他classes定义通用常量的。它看起来像下面这样:

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

而且我想“以 Python 方式”获取所有常量值。如果我使用 CommonNames.__dict__.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:

enum34 backport of the new enum library
from enum import Enum

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

values = [e.value for e in CommonNames]

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

[value for name, value in vars(CommonNames).items() if not name.startswith('_')]