Python 3.4.0 引入enum
,我已经阅读了文档但仍然不知道它的用法。从我的角度来看,enum.Enum
是一个扩展namedtuple
类型,这可能不是真的。所以这些是我想知道的Enum
:
- 何时何地使用
Enum
? - 为什么我们需要
Enum
?有什么优势? - 究竟是什么
Enum
?
Python 3.4.0 引入enum
,我已经阅读了文档但仍然不知道它的用法。从我的角度来看,enum.Enum
是一个扩展namedtuple
类型,这可能不是真的。所以这些是我想知道的Enum
:
Enum
?Enum
?有什么优势?Enum
?1. 何时何地使用枚举?
例如,星期几:
class Weekday(Enum):
MONDAY = 1
TUESDAY = 2
WEDNESDAY = 3
THURSDAY = 4
FRIDAY = 5
SATURDAY = 6
SUNDAY = 7
2. 为什么我们需要枚举?有什么优势?
枚举是有利的,因为它们为常量命名,这使代码更具可读性;并且因为单个成员不能被反弹,使得 Python Enums 是半常量(因为它Enum
本身仍然可以被反弹)。
除了更具可读性的代码之外,调试也更容易,因为您可以看到名称和值,而不仅仅是值
可以将所需的行为添加到 Enums
例如,任何使用过datetime模块的人都知道,datetime
并且date
有两种不同的表示星期几:0-6 或 1-7。我们可以向枚举添加一个方法来从or实例Weekday
中提取日期并返回匹配的枚举成员,而不是自己跟踪它:datetime
date
@classmethod
def from_date(cls, date):
return cls(date.isoweekday())
3. Enum 到底是什么?
Enum 是一种类型,其成员被命名为常量,它们都属于(或应该)一个逻辑值组。到目前为止,我已经Enum
为:
- the days of the week
- the months of the year
- US Federal Holidays in a year
FederalHoliday
是我最复杂的;它使用这个配方,并有方法返回给定年份的假期实际发生日期,如果相关日期是假期则返回下一个工作日(或跳过的天数范围包括假期或周末),以及一年的完整日期集。这里是:
class FederalHoliday(AutoEnum):
NewYear = "First day of the year.", 'absolute', Month.JANUARY, 1
MartinLutherKingJr = "Birth of Civil Rights leader.", 'relative', Month.JANUARY, Weekday.MONDAY, 3
President = "Birth of George Washington", 'relative', Month.FEBRUARY, Weekday.MONDAY, 3
Memorial = "Memory of fallen soldiers", 'relative', Month.MAY, Weekday.MONDAY, 5
Independence = "Declaration of Independence", 'absolute', Month.JULY, 4
Labor = "American Labor Movement", 'relative', Month.SEPTEMBER, Weekday.MONDAY, 1
Columbus = "Americas discovered", 'relative', Month.OCTOBER, Weekday.MONDAY, 2
Veterans = "Recognition of Armed Forces service", 'relative', Month.NOVEMBER, 11, 1
Thanksgiving = "Day of Thanks", 'relative', Month.NOVEMBER, Weekday.THURSDAY, 4
Christmas = "Birth of Jesus Christ", 'absolute', Month.DECEMBER, 25
def __init__(self, doc, type, month, day, occurrence=None):
self.__doc__ = doc
self.type = type
self.month = month
self.day = day
self.occurrence = occurrence
def date(self, year):
"returns the observed date of the holiday for `year`"
if self.type == 'absolute' or isinstance(self.day, int):
holiday = Date(year, self.month, self.day)
if Weekday(holiday.isoweekday()) is Weekday.SUNDAY:
holiday = holiday.replace(delta_day=1)
return holiday
days_in_month = days_per_month(year)
target_end = self.occurrence * 7 + 1
if target_end > days_in_month[self.month]:
target_end = days_in_month[self.month]
target_start = target_end - 7
target_week = list(xrange(start=Date(year, self.month, target_start), step=one_day, count=7))
for holiday in target_week:
if Weekday(holiday.isoweekday()) is self.day:
return holiday
@classmethod
def next_business_day(cls, date, days=1):
"""
Return the next `days` business day from date.
"""
holidays = cls.year(date.year)
years = set([date.year])
while days > 0:
date = date.replace(delta_day=1)
if date.year not in years:
holidays.extend(cls.year(date.year))
years.add(date.year)
if Weekday(date.isoweekday()) in (Weekday.SATURDAY, Weekday.SUNDAY) or date in holidays:
continue
days -= 1
return date
@classmethod
def year(cls, year):
"""
Return a list of the actual FederalHoliday dates for `year`.
"""
holidays = []
for fh in cls:
holidays.append(fh.date(year))
return holidays
备注:
Date
来自我的 dbf 包
增强的xrange
(支持一系列日期)也是自定义的,但我认为我没有将它包含在任何地方;dbf
下次我修补它时,我会把它塞进我的包里。
披露:我是Python stdlibEnum
、enum34
backport和Advanced Enumeration ( aenum
) 库的作者。