【问题标题】:Is there a dedicated way to get the number of items in a python `Enum`?是否有专门的方法来获取 python `Enum` 中的项目数?
【发布时间】:2016-03-31 22:47:33
【问题描述】:

说我有这样一个pythonEnum类:

from enum import Enum

class Mood(Enum):
    red = 0
    green = 1
    blue = 2

有没有一种自然的方法可以获取Mood 中的项目总数? (例如无需对其进行迭代,或添加额外的n 项目,或额外的n classproperty。)

enum 模块是否提供这样的功能?

【问题讨论】:

    标签: python python-3.x enums


    【解决方案1】:

    是的。 Enums 拥有一些普通职业没有的额外能力:

    class Example(Enum):
        this = 1
        that = 2
        dupe = 1
        those = 3
    
    print(len(Example))  # duplicates are not counted
    # 3
    
    print(list(Example))
    # [<Example.this: 1>, <Example.that: 2>, <Example.those: 3>]
    
    print(Example['this'])
    # Example.this
    
    print(Example['dupe'])
    # Example.this
    
    print(Example(1))
    # Example.this
    

    【讨论】:

    • 我的枚举(Python 3.4)不是静态的,而是按照here(一种形式的自动枚举)创建的,最后三个命令不适用于这样的枚举。 Python 中有不同的枚举实现吗?
    • 有一个第三方库叫做enum,它和官方3.4的Enum一样,也不是backportadvanced版本。无论您使用什么enum,都不是三个新的之一。
    【解决方案2】:

    你试过print(len(Mood))吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-02
      • 1970-01-01
      • 1970-01-01
      • 2020-02-27
      相关资源
      最近更新 更多