在Python中定义颜色
我有一个问题,可能很简单,也可能很难回答,我不太确定。我想知道在Python中怎么定义颜色。
比如,我想简单地这样做:
myColor = #920310
但是,在Python中,使用'#'符号会把后面的内容变成注释。有没有什么办法可以解决这个问题呢?谢谢,如果这个问题太简单了,我很抱歉。
4 个回答
2
根据你打算如何使用这些值,你有很多选择:
colorString = "#920310"
colorList = [0x93, 0x03, 0x10]
colorTuple = (0x93, 0x03, 0x10)
colorDict = {
"R" : 0x93,
"G" : 0x03,
"B" : 0x10,
}
或者,如果你打算进行多种操作来处理颜色,比如转换成不同的格式,你可以定义一个颜色类:
class Color(object):
def __init__(self, r, g, b):
self._color = (r,g,b)
def get_tuple(self):
return self._color
def get_str(self):
return "#%02X%02X%02X" % self._color
def __str__(self):
return self.get_str()
def get_YUV(self):
# ...
使用示例:
>>> a = Color(0x93, 0x03, 0xAA) # set using hex
>>> print a
#9303AA
>>> b = Color(12, 123, 3) # set using int
>>> print b
#0C7B03
3
myColor = int('920310', 16) #as an integer (assuming an RGB color in hex)
myColor = '#920310' #as a string
from collections import namedtuple
Color = namedtuple("Color", "R G B")
myColor = Color(0x92, 0x03, 0x10)
#as a namedtuple
你可能在寻找很多东西,而且使用它的方法也有很多种。最终,这取决于你想怎么使用这个颜色。
11
如果你想把它当作一个字符串来用,可以这样做:
myColor = '#920310'
如果你实际上想要的是一个 Color
对象,可以这样做:
myColor = Color('#920310')
然后在 Color
的构造函数里进行处理。
如果问题是能不能让 #
不被当作注释,那答案是不能。如果 #
不是注释,那就不再是 Python 语言了。
你可以定义一个自己的、类似 Python 的语言,在 =
后面的 #
不被当作注释(因为那在 Python 里本来就不合法),这样不会破坏任何代码,但在其他地方使用 #
语法时就会导致代码出错。