简体   繁体   English

有没有一种专用的方法来获取python`Enum`中的项目数?

[英]Is there a dedicated way to get the number of items in a python `Enum`?

Say I have such a python Enum class: 说我有一个这样的python Enum类:

from enum import Enum

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

Is there a natural way to get the total number of items in Mood ? 是否有一种自然的方法来获取Mood的项目总数? (like without having to iterate over it, or to add an extra n item, or an extra n classproperty , etc .) (例如,无需迭代它,或添加额外的n项或额外的n classproperty

Does the enum module provide such a functionality? enum模块是否提供这种功能?

Yes. 是。 Enum s have several extra abilities that normal classes do not: Enum具有普通类没有的一些额外功能:

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

您尝试过print(len(Mood))吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM