我有一个简单的Enum
class E(Enum):
A = 'a'
B = 'b'要访问'a',我必须键入E.A.value。然而,value是我从Enum对象中需要的唯一东西。
如何编写Enum,其中'a'仅可由E.A访问
发布于 2019-06-24 19:00:53
我环顾四周,却找不到一个很好的解决方案,就是用你想要使用的Enum类来解决这个问题。但是,如果您愿意回避使用Enum作为超类的想法,您可以将其结合在一起:
class Demo:
# something with a 'value' method in it
def __init__(self, val):
self.value = val
def custom_enum(cls):
# class decorator to get __getattribute__() to work properly
# this is necessary because __getattribute__() only exists as an instance method,
# and there seems to be no direct equivalent for class methods
return cls()
@custom_enum
class E:
# first, define our enumerated variables in a dict
_enums = {
'A': Demo('a'),
'B': Demo('b'),
'chicken': Demo('cluck')
}
# then, override __getattribute__() to first get the key from the dict,
# and return the .value property of it
def __getattribute__(self, key):
# because of the decorator, we can't call self._enums or else we get a RecursionError
# therefore, we need to implicitly subclass `object`, and then
# deliberately invoke object.__getattribute__ on self, to access _enums
my_enums = object.__getattribute__(self, '_enums')
return my_enums[key].value实际上,定义可枚举值就像编辑_enums dict一样简单。一旦您这样做了,它应该按照您希望的大致工作:
>>> E.A
'a'
>>> E.B
'b'
>>> E.chicken
'cluck'从这里开始,您可以修改实现(例如,返回一个AttributeError而不是一个KeyError,或者重写__setattr__(),使枚举值不可设置,等等)。
发布于 2019-07-11 18:47:12
使用int作为值只是一个例子。它实际上应该是一个用户定义的类。
如果您将类/类型与Enum混合,那么只需访问成员本身就会为您提供该类型的一个子类型:
from enum import Enum
class MyClass:
def __init__(self, color):
self.color = color
class MyEnum(MyClass, Enum):
first = 'red'
second = 'green'
third = 'blue'并在使用中:
>>> MyEnum.first
<MyEnum.first: 'red'>
>>> MyEnum.first.color
'red'
>>> type(MyEnum.first)
<enum 'MyEnum'>
>>> isinstance(MyEnum.first, MyClass)
Truehttps://stackoverflow.com/questions/56741740
复制相似问题