Last active
February 26, 2016 12:03
-
-
Save NoobStuff/f19345346006a67585fc to your computer and use it in GitHub Desktop.
RGBA color class using property decorators
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 Color: | |
| ''' RGBA color handler ''' | |
| def __init__(self, hexcode='000000', alpha='00'): | |
| self.hexcode = hexcode | |
| self.alpha = alpha | |
| @property | |
| def hexcode(self): | |
| return ('{:02x}' * 3).format(int(self.r), int(self.g), int(self.b)) | |
| @hexcode.setter | |
| def hexcode(self, hexcode): | |
| self.r = int(hexcode[0:2], base=16) | |
| self.g = int(hexcode[2:4], base=16) | |
| self.b = int(hexcode[4:6], base=16) | |
| @property | |
| def r(self): | |
| return self._r | |
| @r.setter | |
| def r(self, value): | |
| self._r = Color._convert_value(value) | |
| @property | |
| def g(self): | |
| return self._g | |
| @g.setter | |
| def g(self, value): | |
| self._g = Color._convert_value(value) | |
| @property | |
| def b(self): | |
| return self._b | |
| @b.setter | |
| def b(self, value): | |
| self._b = Color._convert_value(value) | |
| @property | |
| def alpha(self): | |
| return self._alpha | |
| @alpha.setter | |
| def alpha(self, value): | |
| self._alpha = Color._convert_value(value) | |
| def __str__(self): | |
| if not self.alpha: | |
| return '{}'.format(self.hexcode).upper() | |
| else: | |
| return '{}{:02x}'.format(self.hexcode, self.alpha).upper() | |
| def __repr__(self): | |
| return 'Color({}, alpha={:02x})'.format(self.hexcode.upper(), self.alpha) | |
| @staticmethod | |
| def _convert_value(value): | |
| if type(value) is str: | |
| value = int(value, base=16) | |
| if value > 255: | |
| raise ValueError('Value must be between 0-255') | |
| return value | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment