2013-10-12 13 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の値である必要はありませんなぜあなたは尋ねるかもしれませんか?なぜなら、私がそのreprを得るとき、<AddressSegment.ordinal: 'N S E W NE NW SE SW'>はちょっと鈍いですが、その情報をdocstringですぐに利用できるようにするのは良い妥協です。ここで

は、列挙型のレシピです:

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をサブクラス化することです、私はさらにそれを拡張したいはずです。

関連する問題