如何在Python的枚举中初始化命名元组

huangapple go评论59阅读模式
英文:

How to initialize named tuple in python enum

问题

以下是您提供的代码部分的翻译:

我有一个Enum它被用作SqlALchemy中的列数据类型但我需要更多的Enum属性以使它能够在代码的其他功能中访问

这是我目前创建的内容

class ServerHealth(Enum):
    """服务器健康状态。"""

    HealthStatus = namedtuple("HealthStatus", ["name", "low_bound", "high_bound"])
    High = HealthStatus(name="High", low_bound=5, high_bound=24)
    Fair = HealthStatus(name="Fair", low_bound=3, high_bound=5)
    Low = HealthStatus(name="Low", low_bound=0, high_bound=3)

    @DynamicClassAttribute
    def value(self):
        return self.name

这也在SqlAlchemy模型的某处使用所以我需要保持它不会破坏-

class Server(Base):
    server_health = Column(ENUM(ServerHealth), nullable=True)

我需要将namedtuple的"name"作为数据库中的列值据我理解value属性由SqlAlchemy使用所以我已经重写了它们value按预期工作

>>>ServerHealth.High.value
"High"

但当我尝试访问low_bound和high_bound时它会出错

>>>ServerHealth.High.low_bound
AttributeError                            Traceback (most recent call last)
Input In [77], in <cell line: 1>()
----> 1 ServerHealth.High.low_bound

AttributeError: 'ServerHealth'对象没有属性'low_bound'

现在我应该重写哪个函数以使其正常工作而不破坏数据库初始化
英文:

I have a Enum which is used as a column datatype in SqlALchemy. But I need more properties of the Enum to make it accessible for the code's other functionality.

This is what I have created till now:

class ServerHealth(Enum):
&quot;&quot;&quot;Status of Server health.&quot;&quot;&quot;

    HealthStatus = namedtuple(&quot;HealthStatus&quot;, [&quot;name&quot;, &quot;low_bound&quot;, &quot;high_bound&quot;])
    High = HealthStatus(name=&quot;High&quot;, low_bound=5, high_bound=24)
    Fair = HealthStatus(name=&quot;Fair&quot;, low_bound=3, high_bound=5)
    Low = HealthStatus(name=&quot;Low&quot;, low_bound=0, high_bound=3)

    @DynamicClassAttribute
    def value(self):
        return self.name

This is used somewhere in sqlalchemy model as well, so I need to keep it the way it doesn't break-

class Server(Base):
    server_health = Column(ENUM(ServerHealth), nullable=True)

I need the "name" of namedtuple as the columns value in DB. As per my understanding the value attribute is used by sqlalchemy, so I have overwritten them and the value works as expected i.e.

&gt;&gt;&gt;ServerHealth.High.value
&quot;High&quot;

but when I try to access low_bound and high_bound it breaks

&gt;&gt;&gt;ServerHealth.High.low_bound
AttributeError                            Traceback (most recent call last)
Input In [77], in &lt;cell line: 1&gt;()
----&gt; 1 ServerHealth.High.low_bound

AttributeError: &#39;ServerHealth&#39; object has no attribute &#39;low_bound&#39;

Now what function should I overwrite in order to get that working without breaking db initialization.

答案1

得分: 1

这是我会这样做的:

class ServerHealth(Enum):
    """
    服务器健康状态。
    """
    def __new__(cls, name, low_bound, high_bound):
        member = object.__new__(cls)
        member._value_ = name
        member.low_bound = low_bound
        member.high_bound = high_bound
        return member

    HIGH = "High", 5, 24
    FAIR = "Fair", 3, 5
    LOW = "Low", 0, 3

在使用中:

>>> ServerHealth.High.low_bound
5

披露:我是Python标准库Enumenum34后端高级枚举(aenum)库的作者。

英文:

This is how I would do it:

class ServerHealth(Enum):
    &quot;&quot;&quot;
    Status of Server health.
    &quot;&quot;&quot;
    def __new__(cls, name, low_bound, high_bound):
        member = object.__new__(cls)
        member._value_ = name
        member.low_bound = low_bound
        member.high_bound = high_bound
        return member
    #
    HIGH = &quot;High&quot;, 5, 24
    FAIR = &quot;Fair&quot;, 3, 5
    LOW = &quot;Low&quot;, 0, 3

and in use:

&gt;&gt;&gt; ServerHealth.High.low_bound
5

Disclosure: I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum) library.

huangapple
  • 本文由 发表于 2023年2月8日 18:03:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/75384124.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定