Consider the code below:
class Color:
RED: "Color"
GREEN: "Color"
BLUE: "Color"
WHITE: "Color"
BLACK: "Color"
def __init__(self, r: int, g: int, b: int) -> None:
self.r = r
self.g = g
self.b = b
Color.RED = Color(255, 0, 0)
Color.GREEN = Color(0, 255, 0)
Color.BLUE = Color(0, 0, 255)
Color.WHITE = Color(255, 255, 255)
Color.BLACK = Color(0, 0, 0)
Here, I am creating a few color definitions, which can be accessed from the Color
class, as well as creating custom color instances. However, it feels a little repetitive needing to declare then instantiate the values in two different places in my file. Optimally, I would do the following, but because it is self-referencing, I get a NameError
.
class Color:
RED = Color(255, 0, 0)
GREEN = Color(0, 255, 0)
BLUE = Color(0, 0, 255)
WHITE = Color(255, 255, 255)
BLACK = Color(0, 0, 0)
def __init__(self, r: int, g: int, b: int) -> None:
self.r = r
self.g = g
self.b = b
Is there a way for me to cleanly define my preset colors in one place whilst maintaining type safety and readability, or is the first example already as good as it's going to get?