在枚举类中声明一个静态变量 [英] Declare a static variable in an enum class

查看:452
本文介绍了在枚举类中声明一个静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个颜色枚举。我希望在枚举类中添加一个辅助方法 toRGB(),该类将枚举的实例转换为RGB对象。作为一种优化,我希望一次将字典创建为静态变量。但是,正确的语法似乎使我难以理解。



有人可以建议正确的方法吗?



<$ p从枚举导入$ p> 枚举

类RGB:
def __init __(self,r,g,b):
pass

类颜色(枚举):
红色= 0
绿色= 1

__tbl = {
红色:RGB(1,0,0),
GREEN:RGB(0,1,0)
}

def toRGB(self):
return self .__ class __.__ tbl [self.value]

c =颜色.RED
print(c.toRGB())

我收到以下错误:

 跟踪(最近一次通话为最后一次):
文件 C:/ Users / user /Desktop/test.py,第20行,< module>
print(c.toRGB())
文件 C:/Users/user/Desktop/test.py,在toRGB
中的第17行,返回self .__ class __.__ tbl [self。 value]
TypeError:颜色对象不支持索引


解决方案

非方法属性成为枚举成员(甚至 tbl )。您可以改用关键字参数:

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

def到RGB(self,tbl = {
RED:RGB(1,0,0),
绿色:RGB(0,1,0)
}):
返回tbl [self.value]

您也可以定义创建类后的属性:

  class Color(Enum):
红色= 0
绿色= 1

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

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


I have an enum for colors. I wish to add a helper method "toRGB()" to the enum class that converts an instance of the enum to an RGB object. As an optimization, I wished to create the dictionary once as a static variable. However, the correct syntax seems to elude me.

Can anyone suggest the right way to do this?

from enum import Enum

class RGB:
    def __init__(self, r, g, b):
        pass

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

    __tbl = {
              RED:   RGB(1, 0, 0),
              GREEN: RGB(0, 1, 0)
            }

    def toRGB(self):
        return self.__class__.__tbl[self.value]

c = Color.RED
print(c.toRGB())

I get the following error:

Traceback (most recent call last):
  File "C:/Users/user/Desktop/test.py", line 20, in <module>
    print(c.toRGB())
  File "C:/Users/user/Desktop/test.py", line 17, in toRGB
    return self.__class__.__tbl[self.value]
TypeError: 'Color' object does not support indexing

解决方案

Non-method attributes become enum members (even tbl). You can use a keyword argument instead:

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]

Alternatively, you can define the attribute after class creation:

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)
}

这篇关于在枚举类中声明一个静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆