【问题标题】:Getting all constants within a class in python在python中获取类中的所有常量
【发布时间】:2015-04-21 10:40:37
【问题描述】:

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

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 ...

我不想要的。

我希望能够获取所有值,因为此代码稍后会更改,我希望其他地方知道这些更改。

【问题讨论】:

    标签: python class python-2.7 constants


    【解决方案1】:

    您必须通过过滤名称来明确过滤掉那些:

    [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 中添加的新 enum libraryenum34 backport

    from enum import Enum
    
    class CommonNames(Enum):
        C1 = 'c1'
        C2 = 'c2'
        C3 = 'c3'
    
    values = [e.value for e in CommonNames]
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2018-02-03
        • 2015-09-10
        • 1970-01-01
        • 2022-11-24
        • 2023-03-03
        • 2015-09-30
        • 1970-01-01
        • 1970-01-01
        • 2011-02-20
        相关资源
        最近更新 更多