我想让一个具有保留字作为成员的python Enum 工作。
class Test(Enum):
one = "one"
is_ = "is"
我想自定义__name__
以返回通常的语法
>>> print(Test.is_.name)
is
那么我该如何定制__name__
,__getattribute__
或者__getattr__
实现这个呢?
我想让一个具有保留字作为成员的python Enum 工作。
class Test(Enum):
one = "one"
is_ = "is"
我想自定义__name__
以返回通常的语法
>>> print(Test.is_.name)
is
那么我该如何定制__name__
,__getattribute__
或者__getattr__
实现这个呢?
它存储在一个下划线变量中:
>>> Test.is_._name_ = 'is'
>>> Test.is_.name
'is'
这也将修复 repr,并且按成员值调用仍然有效:
>>> list(Test)
[<Test.one: 'one'>, <Test.is: 'is'>]
>>> Test('is')
<Test.is: 'is'>
当然,属性访问仍然必须使用声明的名称,否则会出现语法错误。
要启用按成员名称调用,请将其修补到地图中:
>>> Test.is_._name_ = 'is'
>>> Test._member_map_['is'] = Test.is_
>>> Test['is']
<Test.is: 'is'>
如果您在这里需要的不仅仅是一个简单的别名,那么您可能想要删除原始名称和/或注意保留成员映射中的顺序。
您可以使用以下Functional API
代替:
Test = Enum('Test', [('one', 'one'), ('is', 'is'), ('is_', 'is')])
并在使用中:
>>> Test.one
<Test.one: 'one'>
>>> Test.is
File "<stdin>", line 1
test.is
^
SyntaxError: invalid syntax
>>> Test.is_
<Test.is: 'is'>
>>> Test['is']
<Test.is: 'is'>
>>> Test['is_']
<Test.is: 'is'>
>>> Test('is')
<Test.is: 'is'>
>>> list(Test)
[<Test.one: 'one'>, <Test.is: 'is'>]