简体   繁体   English

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

[英]How can I set a default value for an enum attribute of a recordclass dataobject?

recordclass dataobjects can handle enum attributes just fine, unless you need to set a default value, which results in a SyntaxError (as of version 0.17.5): 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

Is there a workaround for this issue?这个问题有解决方法吗?

Assuming the example in the question is accurate, you'll need to override the stardand Enum.__repr__() :假设问题中的示例是准确的,您需要覆盖标准和Enum.__repr__()

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

Since 0.18 one may use default value of any type.从 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM