파이썬 3.4에는 새로운 enum 모듈과 Enum 데이터 타입이 있습니다. 아직 3.4로 전환 할 수없는 경우 Enum has been backported.enums에 docstrings을 넣으려면 어떻게해야합니까?
거의 모든 파이썬 개체 에서처럼 열거 형 멤버가 docstrings을 지원하므로이 개체를 설정하고 싶습니다. 쉽게 할 수있는 방법이 있습니까?
파이썬 3.4에는 새로운 enum 모듈과 Enum 데이터 타입이 있습니다. 아직 3.4로 전환 할 수없는 경우 Enum has been backported.enums에 docstrings을 넣으려면 어떻게해야합니까?
거의 모든 파이썬 개체 에서처럼 열거 형 멤버가 docstrings을 지원하므로이 개체를 설정하고 싶습니다. 쉽게 할 수있는 방법이 있습니까?
예, 지금까지 제가 가장 좋아하는 요리법입니다. 보너스로 정수 값을 지정할 필요도 없습니다.
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,))
내가 __new__
에 __init__
대신에 인수를 처리하는 이유는 하위 클래스 AutoEnum
쉽게 나는 그것을 더 확장하려는해야하는 것입니다 :
는 여기에 열거 대한 조리법입니다.