Skip to content

Instantly share code, notes, and snippets.

@pythonhacker
Last active March 12, 2026 04:40
Show Gist options
  • Select an option

  • Save pythonhacker/4757e808fc1a0825f15440f2db602add to your computer and use it in GitHub Desktop.

Select an option

Save pythonhacker/4757e808fc1a0825f15440f2db602add to your computer and use it in GitHub Desktop.
RGB Color class with a custom RGBColor attribute representing color
class RGBColor(int):
def __new__(cls, value):
if not value in range(0, 256):
raise ValueError("RGB values must be in range {0...255}")
# Create the integer instance
return super().__new__(cls, value)
class ColorAttrCustom(Color):
""" Color class with full attribute validation and custom color type """
def __init__(self, r=0, g=0, b=0):
# __init__ doesn't need local validation
self.r = RGBColor(r)
self.g = RGBColor(g)
self.b = RGBColor(b)
def __setattr__(self, name, value):
if name in ("r", "g", "b"):
if type(value) is int:
# Color range validation here
value = RGBColor(value)
elif type(value) is not RGBColor:
raise ValueError("RGB value should be of type int or RGBColor")
super().__setattr__(name, value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment