[英]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.