[英]How can I have elements in an Enum evaluate as their value by default?
[英]How can I set a default value for an enum attribute of a recordclass dataobject?
recordclass dataobjects 可以很好地處理枚舉屬性,除非你需要設置一個默認值,這會導致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
這個問題有解決方法嗎?
假設問題中的示例是准確的,您需要覆蓋標准和Enum.__repr__()
:
class Color(Enum):
#
def __repr__(self):
return f'{self.__class__.__name__}.{self._name_}'
#
RED = auto()
從 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'>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.