我有一个类,它主要用于为其他类定义通用常量。它看起来像下面这样:
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/