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

标签 python class python-2.7 constants

我有一个类,它主要用于为其他类定义通用常量。它看起来像下面这样:

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']

对于像这样的枚举,你最好使用 enum34 backport新的 enum library添加到 Python 3.4:

from enum import Enum

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

values = [e.value for e in CommonNames]

关于python - 在python中获取类中的所有常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28617339/

相关文章:

Python 将字符串输入与现有字典匹配的简单方法

不能子类化的 JavaScript 类

python - 从python中的文本文件初始化字典

Python 编程 : how to eval values from dictionary?

Python/ Pandas -ValueError : Incompatible indexer with Series

python - 使用枚举作为类中的标志,Python

c++ - 将对象指针 vector 传递给类 (C++)

javascript - 类型错误 : "stack" is read-only

linux - 安装依赖 SciKit/NumPy/SciPy

python - 导入错误: No module named connector