Python Enum,何时何地使用?

标签 python enums python-3.4

Python 3.4.0 引入了enum,我看过doc但仍然不知道它的用途。从我的角度来看, enum.Enum 是一个扩展的 namedtuple 类型,这可能不是真的。所以这些是我想知道的关于 Enum 的内容:

  1. 何时何地使用 Enum
  2. 为什么我们需要 Enum?有什么优势?
  3. 枚举到底是什么?

最佳答案

1. When and where to use enums?

  • 当您有一个变量采用一组有限的可能值中的一个时。

例如,星期几:

class Weekday(Enum):
    MONDAY = 1
    TUESDAY = 2
    WEDNESDAY = 3
    THURSDAY = 4
    FRIDAY = 5
    SATURDAY = 6
    SUNDAY = 7

2. Why do we need enum? What are the advantages?

  • 枚举是有利的,因为它们为常量命名,这使代码更具可读性;并且由于单个成员不能被反弹,使得 Python Enums 成为半常量(因为 Enum 本身仍然可以被反弹)。

  • 除了更易读的代码之外,调试也更容易,因为您可以看到名称和值,而不仅仅是值

  • 可以将所需的行为添加到枚举中

例如,任何使用过 datetime 的人模块知道,datetimedate 有两种不同的表示星期几:0-6 或 1-7。我们可以向 Weekday 枚举添加一个方法来从 datetimedate 实例中提取日期并返回匹配的枚举成员:

    @classmethod
    def from_date(cls, date):
        return cls(date.isoweekday())

3. What exactly is Enum?

  • 枚举是 type ,其成员被命名为常量,它们都属于(或应该)一个逻辑值组。到目前为止,我已经为:

    创建了 Enums:
    - 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, 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

注意事项:

关于Python Enum,何时何地使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22586895/

相关文章:

c - 枚举 c 中的关联值

python - 检查 python 列表中的序列

java - 为什么 Oracle Java 提供的答案在寻址枚举集时使用私有(private)静态修饰符?

python - 如何修复pycharm中的python控制台错误?

objective-c - 从混合语言项目中的枚举元素初始化一个 NSNumber

python - 如何删除(或取消网格)存储在列表中的 Tkinter GUI 对象 (Python)

python - 名称错误 : name 'argv' is not defined

python - __iter__ 方法的主体有什么意义?

python pandas groupby 排序

python - 如何在 Python 中仅清除一个变量的 os.environ 值