我有颜色的枚举。我希望将一个助手方法“ torgb()”添加到将枚举实例转换为RGB对象的枚举类中。作为优化,我希望将字典创建为静态变量。但是,正确的语法似乎使我感到不安。

问题描述 投票:0回答:5

python 3.7,使用

_ignore_
字段:
https://docs.python.org/3/library/enum.html

class Color(Enum):
    _ignore_ = ['_tbl']
    _tbl = {}  # nice for the type checker, but entirely ignored!


Color._tbl = {}  # actually creates the attribute
python python-3.x enums
5个回答
25
投票
Non-Method属性成为枚举成员(甚至是

tbl

)。您可以使用关键字参数:
class Color(Enum): RED = 0 GREEN = 1 def toRGB(self, tbl={ RED: RGB(1, 0, 0), GREEN: RGB(0, 1, 0) }): return tbl[self.value]

,您可以在类创建后定义属性:
class Color(Enum):
    RED = 0
    GREEN = 1

    def toRGB(self):
        return self._tbl[self]

Color._tbl = {
    Color.RED:   RGB(1, 0, 0),
    Color.GREEN: RGB(0, 1, 0)
}

14
投票

我们无法从您的示例中分辨出
0

1

2

,...,是有意义的价值观还是位置持有人,但是如果它们只是位置持有人,那么最好的解决方案是丢弃它们并将
RGB
值直接用作

1
投票
and and and and and the the

class Color(Enum): RED = 1, 0, 0 GREEN = 0, 1, 0 BLUE = 0, 0, 1

Enum
如果成员与他们的
value
值分开,则可以使用
newaenum库
并解决这样的问题:
rgb

使用:

from aenum import Enum, NamedTuple RGB = NamedTuple('RGB', 'r g b') class Color(Enum, init='value rgb'): RED = 1, RGB(1,0,0) GREEN = 2, RGB(0,1,0) BLUE = 3, RGB(0,0,1)

    
如果您想要的是类型转换,则可以将
>>> Color.RED
<Color.RED: 1>

>>> Color.RED.rgb
RGB(r=1, g=0, b=0)
类用作枚举值: RGB

您还可以跳过
from enum import Enum

class RGB:
    def __init__(self, r, g, b):
        # Check your inputs
        self.r = r
        self.g = g
        self.b = b

    def __str__(self):
        return f"{self.r} {self.g} {self.b}"

class Color(Enum):
    RED = RGB(1, 0, 0)
    GREEN = RGB(0, 1, 0)

    def toRGB():
        return c.value

c = Color.RED
print(c.toRGB())
助手方法,然后简单地写

toRGB

以不同的方式来实现一个子类的静态类变量是使用单例模式:

1
投票
Color.RED.value

注意,您不能使用诸如
Enum

class Color(str, Enum):
    RED = "red"
    GREEN = "green"

    def __new__(cls, value):
        if not hasattr(cls, "instance"):
            cls.__tbl = {"red": RGB(1, 0, 0), "green": RGB(0, 1, 0)}
        obj = str.__new__(cls, value)
        return Enum.__new__(cls, obj)
等的枚举实例(它们尚不存在),因此我改用字符串标识符。我通常更喜欢第一个解决方案。我的代码看起来像这样,因为它需要精确加载一个大数据集。

现在,您的代码完全很好,并且可以做您想要的。这是因为在定义枚举值时忽略了以双重下划线开头的名称。
当您不想以双重下划线开始您的名字时,是:

将您属性的值分配在

RED

中。
使用

GREEN
属性
将属性声明为被忽略(请注意,类型的Checker通常在编写时不支持此用法)。
将枚举类别的属性放置而不是成员。

    


0
投票
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.