Python Enum,何时何地使用? [英] Python Enum, when and where to use?

查看:28
本文介绍了Python Enum,何时何地使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 3.4.0 引入了 enum,我已经阅读了 doc 但仍然不知道它的用法.在我看来,enum.Enum 是一个扩展的 namedtuple 类型,这可能不是真的.所以这些是我想了解的关于 Enum 的内容:

  1. 何时何地使用Enum?
  2. 为什么我们需要Enum?有什么优势?
  3. 究竟什么是Enum?

解决方案

1.何时何地使用枚举?

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

例如,星期几:

class 工作日(枚举):星期一 = 1星期二 = 2星期三 = 3星期四 = 4星期五 = 5星期六 = 6星期日 = 7

<块引用>

2.为什么我们需要枚举?有什么优势?

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

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

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

例如,作为任何使用过日期时间 模块知道,datetimedate 有两种不同的表示星期几:0-6 或 1-7.我们可以向 Weekday 枚举添加一个方法,而不是自己跟踪它,以从 datetimedate 实例中提取日期并返回匹配的枚举成员:

 @classmethoddef from_date(cls, 日期):返回 cls(date.isoweekday())

<块引用>

3.枚举究竟是什么?

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

    创建了 Enums

    - 星期几- 一年中的几个月- 一年中的美国联邦假期

FederalHoliday 是我最复杂的;它使用这个食谱,并有方法返回给定年份的假期实际发生日期,即下一个业务day 如果所讨论的日期是假期(或者跳过的天数范围包括假期或周末),以及一年的完整日期集.这是:

class FederalHoliday(AutoEnum):NewYear = "一年中的第一天.", 'absolute', Month.JANUARY, 1MartinLutherKingJr = "民权领袖的诞生.", 'relative', Month.JANUARY, Weekday.MONDAY, 3President = "Birth of George Washington", 'relative', Month.FEBRUARY, Weekday.MONDAY, 3Memorial = "阵亡将士的记忆", 'relative', Month.MAY, Weekday.MONDAY, 5Independence = "独立宣言", 'absolute', Month.JULY, 4Labor = "美国劳工运动", 'relative', Month.SEPTEMBER, Weekday.MONDAY, 1哥伦布 = "发现美洲", 'relative', Month.OCTOBER, Weekday.MONDAY, 2退伍军人 = "对武装部队服役的认可", 'relative', Month.NOVEMBER, 11, 1感恩节 = "感谢日", 'relative', Month.NOVEMBER, Weekday.THURSDAY, 4圣诞节 = "耶稣基督的诞生", '绝对', Month.December, 25def __init__(self, doc, type, month, day,occurrence=None):self.__doc__ = docself.type = 类型self.month = 月self.day = 天self.occurrence = 发生定义日期(自己,年份):返回`year`的假期观察日期"如果 self.type == 'absolute' 或 isinstance(self.day, int):假期 = 日期(年,自.月,自.日)如果 Weekday(holiday.isoweekday()) 是 Weekday.SUNDAY:假期 = 假期.replace(delta_day=1)回程假期days_in_month = days_per_month(year)target_end = self.occurrence * 7 + 1如果 target_end >days_in_month[self.month]:target_end = days_in_month[self.month]target_start = target_end - 7target_week = list(xrange(start=Date(year, self.month, target_start), step=one_day, count=7))在 target_week 假期:如果 Weekday(holiday.isoweekday()) 是 self.day:回程假期@类方法def next_business_day(cls, date, days=1):"""从日期返回下一个天"工作日."""假期 = cls.year(date.year)年 = 设置([日期.年])而天 >0:日期 = date.replace(delta_day=1)如果 date.year 不是年:Holiday.extend(cls.year(date.year))年.添加(日期.年)如果 Weekday(date.isoweekday()) 在 (Weekday.SATURDAY, Weekday.SUNDAY) 或日期在假期:继续天 -= 1归期@类方法定义年份(cls,年份):"""返回 `year` 的实际 FederalHoliday 日期列表."""假期 = []对于 cls 中的 fh:假期.追加(fh.date(年))回程假期

<小时>

注意事项:

Python 3.4.0 introduced enum, I've read the doc but still don't know the usage of it. From my perspective, enum.Enum is an extended namedtuple type, which may not be true. So these are what I want to know about Enum:

  1. When and where to use Enum?
  2. Why do we need Enum? What are the advantages?
  3. What exactly is an Enum?

解决方案

1. When and where to use enums?

  • When you have a variable that takes one of a limited set of possible values.

For example, the days of the week:

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?

  • Enums are advantageous because they give a name to a constant, which makes code more readable; and because the individual members cannot be rebound, making Python Enums semi-constant (because the Enum itself could still be rebound).

  • Besides more readable code, debugging is also easier as you see a name along with the value, not just the value

  • Desired behavior can be added to Enums

For example, as anyone who has worked with the datetime module knows, datetime and date have two different representations for the days of the week: 0-6 or 1-7. Rather than keep track of that ourselves we can add a method to the Weekday enum to extract the day from the datetime or date instance and return the matching enum member:

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

3. What exactly is Enum?

  • Enum is a type, whose members are named constants, that all belong to (or should) a logical group of values. So far I have created Enums for:

    - the days of the week
    - the months of the year
    - US Federal Holidays in a year
    

FederalHoliday is my most complex; it uses this recipe, and has methods to return the actual date the holiday takes place on for the year given, the next business day if the day in question is a holiday (or the range of days skipped includes the holiday or weekends), and the complete set of dates for a year. Here it is:

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


Notes:

这篇关于Python Enum,何时何地使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆