2

我想让一个具有保留字作为成员的python Enum 工作。

class Test(Enum):

    one = "one"
    is_ = "is"

我想自定义__name__以返回通常的语法

>>> print(Test.is_.name)
is

那么我该如何定制__name____getattribute__或者__getattr__实现这个呢?

4

2 回答 2

2

它存储在一个下划线变量中:

>>> 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'>

如果您在这里需要的不仅仅是一个简单的别名,那么您可能想要删除原始名称和/或注意保留成员映射中的顺序。

于 2018-12-15T09:29:00.063 回答
1

您可以使用以下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'>]
于 2018-12-17T09:23:24.947 回答