Python 使用常量和方法初始化
我正在编写一个python模块,它应该包含一些常量,我正在将这些常量分组到一个类中,如下所示:Python 使用常量和方法初始化,python,Python,我正在编写一个python模块,它应该包含一些常量,我正在将这些常量分组到一个类中,如下所示: (myModule.py) class Colors: PURPLE = (0.549,0.110,0.706) GREEN = (0.188,0.463,0.165) BLUE = (0.125,0.247,0.600) ORANGE = (0.961,0.533,0.114) 因此,在我的主程序中,我可以使用 (mainProgram.py) import m
(myModule.py)
class Colors:
PURPLE = (0.549,0.110,0.706)
GREEN = (0.188,0.463,0.165)
BLUE = (0.125,0.247,0.600)
ORANGE = (0.961,0.533,0.114)
因此,在我的主程序中,我可以使用
(mainProgram.py)
import myModule as mm
niceColor = mm.Colors.PURPLE
到目前为止,一切顺利
现在,我想给这个类的所有常量成员添加一个方法,这样我就可以这样调用它们:
brightColor = mm.Colors.PURPLE.lighten(0.8)
darkColor = mm.Colors.PURPLE.darken(0.6)
我知道如何编写函数变亮
和变暗
,但我不知道如何添加它们以获得想要的功能
非常感谢您可以添加一个名为color的类,该类具有名为lighte的方法
class color:
def __init__(self, color):
self.color = color
def lighten(self, light):
pass
而不是做:
PURPLE = (0.549,0.110,0.706)
做
通过这种方式,您应该能够从color类调用该方法来扩展@jotes answer-要使它仍然像您在不调用darken时使用的元组一样,您可以对
元组
进行子类化,并从中添加功能
类颜色(元组):
def(自我):
通过
def变暗(自):
通过
类别颜色:
紫色=颜色([0.549,0.110,0.706])
#……等等
您需要为此设置一个类。由于处理元组,最好的解决方案可能是扩展tuple
(或者更好的namedtuple
):
从集合导入namedtuple
类别颜色(名称为“RGB”、“r”、“g”、“b”):
def应用功能(自身、功能):
返回颜色(*映射(函数,自身))
def(自我、价值):
返回自应用函数(λx:x*(1+值))
def变暗(自身,值):
返回自应用函数(λx:x/(1+值))
类别颜色:
紫色=颜色(0.549,0.110,0.706)
绿色=颜色(0.188,0.463,0.165)
蓝色=颜色(0.125,0.247,0.600)
橙色=颜色(0.961,0.533,0.114)
然后,您可以执行以下操作:
打印(颜色:紫色)
颜色(r=0.549,g=0.11,b=0.706)
>>>浅紫色=颜色。紫色。变亮(0.8)
>>>印刷品(浅紫色)
颜色(r=0.9882000000000001,g=0.198,b=1.2708)
正如您所看到的,这还不是完美的,因为变亮
和变暗
方法太简单了,您只需要更改传递给应用函数
的lambda就可以得到更干净的东西(例如使用min
来限制值的增长幅度)
使用名为双的
的优点是,通过调用浅紫色.r
,g
,b
,您可以从任何颜色直接访问r
,b
,例如,light\u purple.r
,以下内容应为您提供所需的功能。rgb
是一个类属性,而lighting
和darken
是类方法,这意味着您不必在Colors
对象的实例中创建来执行亮显和暗显操作
class Colors(object):
@classmethod
def lighten(cls, scale):
return tuple([val * scale for val in cls.rgb]) # or whatever you need to do
@classmethod
def darken(cls, scale):
return tuple([val * scale for val in cls.rgb]) # or whatever you need to do
class Purple(Colors):
rgb = (0.549,0.110,0.706)
class Green(Colors):
rgb = (0.188,0.463,0.165)
class Blue(Colors):
rgb = (0.125,0.247,0.600)
class Orange(Colors):
rgb = (0.961,0.533,0.114)
您可以使用以下方法进行测试:
print(Orange.lighten(0.5))
print(Orange.darken(1.5))
使用NamedTuple
from typing import NamedTuple
class Color(NamedTuple):
r: float
g: float
b: float
def lighten(self):
"""perform lightening logic here"""
mm.Colors.PURPLE.lighting
会引发属性错误
,因为Colors.PURPLE
是一个浮动
,而不是类
或类型
,用于访问实际的颜色值,你要么需要向color
类添加更多方法,要么以mm.Colors.PURPLE.color
的形式访问它们。我相信OP是说他们想要一个带有加亮加暗方法的元组,这样他们仍然可以访问基值,而不需要额外的方法调用。
from typing import NamedTuple
class Color(NamedTuple):
r: float
g: float
b: float
def lighten(self):
"""perform lightening logic here"""