Python枚举类(Enum)学习

An enumeration is a set of symbolic names (members) bound to unique, constant values. Within an enumeration, the members can be compared by identity, and the enumeration itself can be iterated over.(enum--《The Python Standard Library》)

枚举是一组绑定到唯一常量值的符号名称(成员)。在枚举中,可以通过标识来比较成员,并且可以迭代枚举本身。

from enum import Enum

Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))
for name, member in Month.__members__.items():
    print(name, '=>', member, ',', member.value)

value属性则是自动赋给成员的int常量,默认从1开始计数。 

from enum import Enum, unique

@unique
class Weekday(Enum):

 从Enum派生出自定义类

@unique装饰器可以帮助我们检查保证没有重复值。

发布了3 篇原创文章 · 获赞 1 · 访问量 847

猜你喜欢

转载自blog.csdn.net/Cocoa_Cat/article/details/88706033
今日推荐