Created
March 12, 2026 04:50
-
-
Save pythonhacker/b1ea624deac8ece797138e4c02197723 to your computer and use it in GitHub Desktop.
RGB Color class with validation using a custom descriptor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class IntRange: | |
| """ Custom integer range class using descriptors """ | |
| def __init__(self, min_val, max_val): | |
| self._range = range(min_val, max_val) | |
| def __set_name__(self, owner, name): | |
| self.name = "_" + name | |
| def __get__(self, obj, objtype=None): | |
| return getattr(obj, self.name) | |
| def __set__(self, obj, value): | |
| if not isinstance(value, int): | |
| raise TypeError("Error - must be integer") | |
| if not value in self._range: | |
| raise ValueError(f"{value} not in range {self._range}") | |
| setattr(obj, self.name, value) | |
| class ColorDesc(Color): | |
| r = IntRange(0, 255) | |
| g = IntRange(0, 255) | |
| b = IntRange(0, 255) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment