Python 3.4.0介绍enum
,我已经阅读doc但仍然不知道它的用法。从我的角度来看,枚举是一种扩展的namedtuple
类型,可能不是真的。所以这些是我想知道的枚举:
答案 0 :(得分:22)
1。何时何地使用枚举?
例如,一周中的几天:
class Weekday(Enum):
MONDAY = 1
TUESDAY = 2
WEDNESDAY = 3
THURSDAY = 4
FRIDAY = 5
SATURDAY = 6
SUNDAY = 7
2。为什么我们需要枚举?有什么好处?
枚举是有利的,因为它们为常量命名,使代码更具可读性;并且因为个别成员无法反弹,使得Python Enums半常数(因为Enum
本身仍然可以反弹)。
除了更易读的代码外,调试也更容易,因为您会看到名称和值,而不仅仅是值
可以将所需行为添加到枚举
例如,正如使用datetime模块的任何人都知道的那样,datetime
和date
对一周中的几天有两种不同的重复:0-6或1-7 。我们可以在Weekday
枚举中添加一个方法,以便从datetime
或date
实例中提取日期并返回匹配的枚举成员,而不是跟踪自己:
@classmethod
def from_date(cls, date):
return cls(date.isoweekday())
3。究竟究竟是什么?
枚举是type,其成员名为常量,它们都属于(或应该)逻辑值组。到目前为止,我已经创建了Enum
s:
- the days of the week
- the months of the year
- US Federal Holidays in a year
FederalHoliday
是我最复杂的;它使用this recipe,并且有方法可以返回给定年份假日发生的实际日期,如果有问题的日子是假日,则返回下一个工作日(或者跳过的天数包括假日或周末) ),以及一年的完整日期。这是:
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, occurance=None):
self.__doc__ = doc
self.type = type
self.month = month
self.day = day
self.occurance = occurance
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.occurance * 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
来自my dbf package
增强型xrange
(支持一系列日期)也是自定义的,但我认为我没有把它包含在任何地方;下次我修补它时,我会将它填入我的dbf
包中。
披露:我是Python stdlib Enum
,enum34
backport和Advanced Enumeration (aenum
)图书馆的作者。
答案 1 :(得分:2)
Enum
背后的PEP 435 ("Adding an Enum type to the Python standard library")有很多examples作者希望如何使用它。
更多评论here。