Eth*_*man 10 enums python-2.7 python-3.x
Python 3.4有一个新的枚举模块和Enum数据类型.如果您还无法切换到3.4,则Enum已被移植.
由于Enum成员支持docstrings,就像所有python对象一样,我想设置它们.有一个简单的方法吗?
lyn*_*fox 19
对于 2022 年的许多 IDE,以下内容将填充智能感知:
class MyEnum(Enum):
"""
MyEnum purpose and general doc string
"""
VALUE = "Value"
"""
This is the Value selection. Use this for Values
"""
BUILD = "Build"
"""
This is the Build selection. Use this for Buildings
"""
Run Code Online (Sandbox Code Playgroud)
VSCode 中的示例:
是的,这是迄今为止我最喜欢的食谱。另外,不必指定整数值。这是一个例子:
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"
Run Code Online (Sandbox Code Playgroud)
您可能会问,为什么我不仅仅拥有"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.
"""
#
def __new__(cls, *args):
"""Ignores arguments (will be handled in __init__."""
value = len(cls) + 1
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,))
Run Code Online (Sandbox Code Playgroud)
并在使用中:
>>> list(AddressSegment)
[<AddressSegment.ordinal: 1>, <AddressSegment.secondary: 2>, <AddressSegment.misc: 3>, <AddressSegment.street: 4>]
>>> AddressSegment.secondary
<AddressSegment.secondary: 2>
>>> AddressSegment.secondary.__doc__
'apt bldg floor etc'
Run Code Online (Sandbox Code Playgroud)
我处理in __init__
而不是in的原因__new__
是,AutoEnum
如果我想进一步扩展子类,则可以简化子类。