如何为记录类数据对象的枚举属性设置默认值



recordclass数据对象可以很好地处理枚举属性,除非您需要设置默认值,这会导致SyntaxError(从0.17.5版本起(:


In [1]: from enum import Enum, auto
In [2]: from recordclass import dataobject
In [3]: class Color(Enum):
...:     RED = auto()
...: 
In [4]: class Point(dataobject):
...:     x: float
...:     y: float
...:     color: Color
...: 
In [5]: pt = Point(1, 2, Color.RED)
In [6]: pt
Out[6]: Point(x=1, y=2, color=<Color.RED: 1>)
In [7]: class Point(dataobject):
...:     x: float
...:     y: float
...:     color: Color = Color.RED
...: 
...: 
Traceback (most recent call last):
...
File "<string>", line 2
def __new__(_cls_, x, y, color=<Color.RED: 1>):
^
SyntaxError: invalid syntax

有解决这个问题的方法吗?

由于0.18,可以使用任何类型的默认值。

from recordclass import dataobject
from enum import Enum, auto
class Color(Enum):
RED = auto()
class Point(dataobject):
x: float
y: float
color: Color = Color.RED
>>> pt = Point(1,2)
>>> pt
Point(x=1, y=2, color=<Color.RED: 1>)
>>> pt.color
<Color.RED: 1>
>>> type(pt.color)
<enum 'Color'>

假设问题中的示例是准确的,则需要覆盖标准和Enum.__repr__():

class Color(Enum):
#
def __repr__(self):
return f'{self.__class__.__name__}.{self._name_}'
#
RED = auto()

最新更新