summaryrefslogtreecommitdiffstats
path: root/color.py
diff options
context:
space:
mode:
Diffstat (limited to 'color.py')
-rw-r--r--color.py50
1 files changed, 27 insertions, 23 deletions
diff --git a/color.py b/color.py
index a38c28b..058abb4 100644
--- a/color.py
+++ b/color.py
@@ -4,41 +4,45 @@ import colorsys
import math
class Vector(object):
- """N-dimensional vector class."""
- def __init__(self, *components):
+ __slots__ = ('x', 'y', 'z')
+
+ """3-dimensional vector class."""
+ def __init__(self, x, y, z):
"""Create a vector from its components."""
- self.components = components
+ self.x = x
+ self.y = y
+ self.z = z
def __add__(self, other):
"""Add two vectors."""
- return self.__class__(
- *map(lambda (x, y): x + y, zip(self.components, other.components))
- )
+ return self.__class__(self.x + other.x, self.y + other.y, self.z + other.z)
def __sub__(self, other):
"""Subtract two vectors."""
- return self.__class__(
- *map(lambda (x, y): x - y, zip(self.components, other.components))
- )
+ return self.__class__(self.x - other.x, self.y - other.y, self.z - other.z)
- def __mul__(self, other):
+ def __mul__(self, scalar):
"""Multiply a vector by a constant."""
- return self.__class__(*map(lambda x: x * other, self.components))
+ return self.__class__(self.x * scalar, self.y * scalar, self.z * scalar)
- def __rmul__(self, other):
+ def __rmul__(self, scalar):
"""Multiply a constant by a vector."""
- return self * other
+ return self * scalar
def __abs__(self):
"""Return the 2-norm of the vector."""
- return math.sqrt(sum(map(lambda x: x * x, self.components)))
+ return math.sqrt(self.x * self.x + self.y * self.y + self.z * self.z)
def __truediv__(self, scalar):
"""Return self * 1 / scalar."""
return self * (1 / scalar)
def __eq__(self, other):
- return self.components == other.components
+ return self.x == other.x and self.y == other.y and self.z == other.z
+
+ @property
+ def components(self):
+ return (self.x, self.y, self.z)
class HSV(Vector):
@@ -49,19 +53,19 @@ class HSV(Vector):
def to_RGB(self):
"""Convert to an RGB vector."""
- return RGB(*colorsys.hsv_to_rgb(*self.components))
+ return RGB(*colorsys.hsv_to_rgb(self.x, self.y, self.z))
def h(self):
"""Return hue."""
- return self.components[0]
+ return self.x
def s(self):
"""Return saturation."""
- return self.components[1]
+ return self.y
def v(self):
"""Return value."""
- return self.components[2]
+ return self.z
class RGB(Vector):
@@ -72,19 +76,19 @@ class RGB(Vector):
def to_HSV(self):
"""Convert to HSV vector."""
- return HSV(*colorsys.rgb_to_hsv(*self.components))
+ return HSV(*colorsys.rgb_to_hsv(self.x, self.y, self.z))
def r(self):
"""Return red value."""
- return self.components[0]
+ return self.x
def g(self):
"""Return green value."""
- return self.components[1]
+ return self.y
def b(self):
"""Return blue value."""
- return self.components[2]
+ return self.z
red = RGB(1, 0, 0)
green = RGB(0, 1, 0)