python3(三十) Enum

"""  """
__author__ = 'shaozhiqi'

# 当我们需要定义常量时,一个办法是用大写变量通过整数来定义,例如月份:
JAN = 1
FEB = 2
MAR = 3
# 好处是简单,缺点是类型是int,并且仍然是变量

# --------------Enum----------------------------------------------
from enum import Enum

Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))
print(Month.Jan)  # Month.Jan

from enum import unique


# @unique装饰器可以帮助我们检查保证没有重复值。
@unique
class Weekday(Enum):
    Sun = 0  # Sun的value被设定为0
    Mon = 1
    Tue = 2
    Wed = 3
    Thu = 4
    Fri = 5
    Sat = 6


day1 = Weekday.Mon
print(day1)  # Weekday.Mon
print(day1.value)  # 1

for name, member in Weekday.__members__.items():
    print(name, '->', member)
# Sun -> Weekday.Sun
# Mon -> Weekday.Mon
# Tue -> Weekday.Tue
# Wed -> Weekday.Wed
# Thu -> Weekday.Thu
# Fri -> Weekday.Fri
# Sat -> Weekday.Sat

 

posted @ 2019-09-19 16:18  ~清风煮酒~  阅读(237)  评论(0编辑  收藏  举报