如何使用数字键使用枚举?

发布于 2025-01-26 06:41:10 字数 328 浏览 1 评论 0原文

我有一个应该像这样的枚举:

from enum import Enum


class ComponentType(Enum):
    5120 = "<{}b"
    5121 = "<{}B"
    5122 = "<{}h"
    5123 = "<{}H"
    5125 = "<{}I"
    5126 = "<{}f"

显然,这是不起作用的,因为您不能分配给文字。我将如何创建和使用此数据中的枚举?我有一个整数需要与struct.unpack()的格式配对。我知道这可以用字典来完成,可以用枚举完成吗?它会是什么样?

I have an enum that should be something like this:

from enum import Enum


class ComponentType(Enum):
    5120 = "<{}b"
    5121 = "<{}B"
    5122 = "<{}h"
    5123 = "<{}H"
    5125 = "<{}I"
    5126 = "<{}f"

Obviously, this doesn't work because you can't assign to a literal. How would I go about creating and using an enum from this data? I have an integer that needs to pair with a format for struct.unpack(). I know this can be done with a dictionary, can it be done with an enum? What would it look like?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

原谅我要高飞 2025-02-02 06:41:10

词典是您最好的选择。枚举名称成为类的属性,整数不能成为属性的名称。

如果您真的想使用枚举,则可以将名称放入有效的属性名称中,例如预先准备任意字母。

class ComponentType(Enum):
    s5120 = "<{}b"
    s5121 = "<{}B"
    s5122 = "<{}h"
    s5123 = "<{}H"
    s5125 = "<{}I"
    s5126 = "<{}f"

ComponentType.s5120.value  # '<{}b'

A dictionary is your best option here. The enum names become attributes of the class, and an integer cannot be the name of an attribute.

If you really want to use an enum, you could make the names into valid attribute names, like by prepending an arbitrary letter.

class ComponentType(Enum):
    s5120 = "<{}b"
    s5121 = "<{}B"
    s5122 = "<{}h"
    s5123 = "<{}H"
    s5125 = "<{}I"
    s5126 = "<{}f"

ComponentType.s5120.value  # '<{}b'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文