我一直在搞乱python的枚举库,并遇到了一个难题。在文档中,它们显示了auto-numbering enum的示例,其中定义了一些内容:
class Color(AutoNumber):
red = ()
green = ()
...
我想创建一个类似的类,但是该值会自动从成员的名称设置并保留从str
和enum
mixin stuff获得的功能
类似于:
class Animal(MagicStrEnum):
horse = ()
dog = ()
Animal.dog == 'dog' # True
我查看了枚举模块的源代码,并尝试了很多变体,其中包含__new__
和EnumMeta
类
答案 0 :(得分:12)
更新:2017-03-01
在Python 3.6(和
Aenum 2.0
1 )中添加了Flag
和IntFlag
个类;其中一部分是一个新的auto()
helper,这使得这很简单:
>>> class AutoName(Enum):
... def _generate_next_value_(name, start, count, last_values):
... return name
...
>>> class Ordinal(AutoName):
... NORTH = auto()
... SOUTH = auto()
... EAST = auto()
... WEST = auto()
...
>>> list(Ordinal)
[<Ordinal.NORTH: 'NORTH'>, <Ordinal.SOUTH: 'SOUTH'>, <Ordinal.EAST: 'EAST'>, <Ordinal.WEST: 'WEST'>]
原始回答
AutoStr
类的难点在于枚举成员的名称未传递给创建它的代码,因此无法使用。另一个问题是str
是不可变的,因此我们无法在创建后更改这些类型的枚举(例如,使用class decorator)。
最简单的方法是使用Functional API:
Animal = Enum('Animal', [(a, a) for a in ('horse', 'dog')], type=str)
给了我们:
>>> list(Animal)
[<Animal.horse: 'horse'>, <Animal.dog: 'dog'>]
>>> Animal.dog == 'dog'
True
下一个最简单的事情,假设你想为将来的枚举使用创建一个基类,就像我的DocEnem
:
class DocEnum(Enum):
"""
compares equal to all cased versions of its name
accepts a doctring for each member
"""
def __new__(cls, *args):
"""Ignores arguments (will be handled in __init__)"""
obj = object.__new__(cls)
obj._value_ = None
return obj
def __init__(self, doc=None):
# first, fix _value_
self._value_ = self._name_.lower()
self.__doc__ = doc
def __eq__(self, other):
if isinstance(other, basestring):
return self._value_ == other.lower()
elif not isinstance(other, self.__class__):
return NotImplemented
return self is other
def __ne__(self, other):
return not self == other
并在使用中:
class SpecKind(DocEnum):
REQUIRED = "required value"
OPTION = "single value per name"
MULTI = "multiple values per name (list form)"
FLAG = "boolean value per name"
KEYWORD = 'unknown options'
请注意,与第一个选项不同,DocEnum
成员不 str
。
如果你想这么做的话:子类EnumMeta
并在创建成员之前摆弄新的Enum
的类字典:
from enum import EnumMeta, Enum, _EnumDict
class StrEnumMeta(EnumMeta):
def __new__(metacls, cls, bases, oldclassdict):
"""
Scan through `oldclassdict` and convert any value that is a plain tuple
into a `str` of the name instead
"""
newclassdict = _EnumDict()
for k, v in oldclassdict.items():
if v == ():
v = k
newclassdict[k] = v
return super().__new__(metacls, cls, bases, newclassdict)
class AutoStrEnum(str, Enum, metaclass=StrEnumMeta):
"base class for name=value str enums"
class Animal(AutoStrEnum):
horse = ()
dog = ()
whale = ()
print(Animal.horse)
print(Animal.horse == 'horse')
print(Animal.horse.name, Animal.horse.value)
这给了我们:
Animal.horse
True
horse horse
1 披露:我是Python stdlib Enum
,enum34
backport和Advanced Enumeration (aenum
)图书馆的作者。
答案 1 :(得分:1)
也许您正在寻找由Enum
类自动提供的name
属性
>>> class Animal(Enum):
... ant = 1
... bee = 2
... cat = 3
... dog = 4
...
>>> Animal.ant.name == "ant"
True
虽然你真的想要在脚下射击自己。而且我相信这会引入一整套陷阱(我已经消除了最明显的问题)。
from enum import Enum, EnumMeta, _EnumDict
class AutoStrEnumDict(_EnumDict):
def __setitem__(self, key, value):
super().__setitem__(key, key)
class AutoStrEnumMeta(EnumMeta):
@classmethod
def __prepare__(metacls, cls, bases):
return AutoStrEnumDict()
def __init__(self, name, bases, attrs):
super().__init__(name, bases, attrs)
# override Enum.__str__
# can't put these on the class directly otherwise EnumMeta overwrites them
# should also consider resetting __repr__, __format__ and __reduce_ex__
if self.__str__ is not str.__str__:
self.__str__ = str.__str__
class AutoStrNameEnum(str, Enum, metaclass=AutoStrEnumMeta):
pass
class Animal(AutoStrNameEnum):
horse = ()
dog = ()
print(Animal.horse)
assert Animal.horse == "horse"
assert str(Animal.horse) == "horse"
# and not equal to "Animal.horse" (the gotcha mentioned earlier)