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

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

问题描述

Python 3.4.0引入了枚举,我已经阅读了 doc ,但仍然不知道它的用法。从我的角度来看,枚举是一个扩展的 namedtuple 类型,可能不是这样。所以这些是我想知道的枚举:


  1. 什么时候使用枚举?

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

  3. 什么是枚举? >


    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())



    < blockquote>

    3。枚举是什么?





    • 枚举是一个类型,其成员名为常量,全部属于(或应该)逻辑组的价值观。到目前为止,我已经创建了枚举

         - 一周
      - 一年中的几个月
      - 一年的美国联邦假日




    FederalHoliday 是我最复杂的;它使用此配方,并且具有返回假期发生的实际日期在给定的年份,下一个业务如果有关的日子是假日(或跳过的日期范围包括假日或周末),以及一年的完整日期。这里是:

      class FederalHoliday(AutoEnum):
    NewYear =一年中的第一天绝对',月。1月$ 1
    MartinLutherKingJr =民权领袖出身,亲戚,月.JANUARY,Weekday.MONDAY,3
    总统=乔治华盛顿出生 相对,月.FEBRUARY,Weekday.MONDAY,3
    纪念=堕落士兵的记忆,亲戚,月.MAY,平日.MONDAY,5
    独立=独立宣言 绝对,月.JULY,4
    劳工=美国劳工运动,亲属,月.SEPTEMBER,Weekday.MONDAY,1
    哥伦布=美洲发现,亲戚,月.OCTOBER,Weekday.MONDAY,2
    退伍军人=武装部队服务承认,亲戚,月.NOVEMBER,11,1
    感恩节=感谢日,亲戚,月4月8日,圣诞节=耶稣基督的诞生,绝对,月。十二月,25

    def __init __(self,doc,type,month,day,occurrenceance = None):
    self .__ doc__ = doc
    self.type = type
    self.month = month
    self.day = day
    self.occurance =出现

    定义日期(自我,年):
    返回假期的观察日期` year`
    如果self.type =='absolute'或isinstance(self.day,int):
    holiday = Date(year,self.month,self.day)
    如果平日(holiday.isoweekday())是Weekday.SUNDAY:
    holiday = holiday.replace(delta_day = 1)
    返回假期
    days_in_month = days_per_month(year)
    target_end = self。出现* 7 + 1
    如果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))
    在target_week中的假期:
    如果Weekday(holiday.isoweekday())是self.day:
    return holiday

    @classmethod
    def next_business_day(cls,date,days = 1):

    从日期起返回下一个天工作日

    holidays = cls.year(date.year)
    years = set([date.year])
    while days> 0:
    date = date.replace(delta_day = 1)
    如果date.year不是以年为单位:
    holidays.extend(cls.year(date.year))
    年.add(date.year)
    如果Weekday(date.isoweekday())在(Weekday.SATURDAY,Weekday.SUNDAY)或假期的日期:
    continue
    days - = 1
    返回日期

    @classmethod
    def year(cls,year):

    返回year的实际FederalHoliday日期列表。

    holidays = []
    在cls中的fh:
    holidays.append(fh.date(year))
    返回假期






    备注




    Python 3.4.0 introduced enum, I've read the doc but still don't know the usage of it. From my perspective, 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 advatages?
    3. What exactly is 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 represntations 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, 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
    


    Notes:

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

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