2013-10-12 31 views

回答

3

是的,這是我最喜歡的食譜。作爲獎勵,也可以不指定整數值。這裏有一個例子:

class AddressSegment(AutoEnum): 
    misc = "not currently tracked" 
    ordinal = "N S E W NE NW SE SW" 
    secondary = "apt bldg floor etc" 
    street = "st ave blvd etc" 

你可能會問爲什麼我不只是有"N S E W NE NW SE SW"ordinal價值?因爲當我看到<AddressSegment.ordinal: 'N S E W NE NW SE SW'>看起來很笨重,但在文檔字符串中提供這些信息是一個很好的折衷。

下面是枚舉配方:

class AutoEnum(enum.Enum): 
    """ 
    Automatically numbers enum members starting from 1. 

    Includes support for a custom docstring per member. 

    """ 
    __last_number__ = 0 

    def __new__(cls, *args): 
     """Ignores arguments (will be handled in __init__.""" 
     value = cls.__last_number__ + 1 
     cls.__last_number__ = value 
     obj = object.__new__(cls) 
     obj._value_ = value 
     return obj 

    def __init__(self, *args): 
     """Can handle 0 or 1 argument; more requires a custom __init__. 

     0 = auto-number w/o docstring 
     1 = auto-number w/ docstring 
     2+ = needs custom __init__ 

     """ 
     if len(args) == 1 and isinstance(args[0], (str, unicode)): 
      self.__doc__ = args[0] 
     elif args: 
      raise TypeError('%s not dealt with -- need custom __init__' % (args,)) 

我處理這些參數中,而不是在__init____new__原因是爲了讓子類AutoEnum容易,我應該想進一步擴展它。

相關問題