sync from Atlas repo

This commit is contained in:
Luciano Ramalho
2014-11-14 12:03:10 -02:00
parent 661b68b235
commit 6dbc75520f
20 changed files with 2281 additions and 31 deletions

View File

@@ -1,5 +1,5 @@
"""
A multi-dimensional ``Vector`` class, take 6
A multi-dimensional ``Vector`` class, take 6: operator ``+``
A ``Vector`` is built from an iterable of numbers::
@@ -183,19 +183,49 @@ Tests of ``format()`` with spherical coordinates in 2D, 3D and 4D::
'<1.00000, 1.57080, 0.00000, 0.00000>'
Tests of operator `==`::
Basic tests of operator ``+``::
>>> v1 = Vector(range(1, 4))
>>> v2 = Vector([1.0, 2.0, 3.0])
>>> v1 == v2
>>> v1 = Vector([3, 4, 5])
>>> v2 = Vector([6, 7, 8])
>>> v1 + v2
Vector([9.0, 11.0, 13.0])
>>> v1 + v2 == Vector([3+6, 4+7, 5+8])
True
>>> v3 = Vector([1, 2])
>>> v1 + v3 # short vectors are filled with 0.0 on addition
Vector([4.0, 6.0, 5.0])
Tests of ``+`` with mixed types::
>>> v1 + (10, 20, 30)
Vector([13.0, 24.0, 35.0])
>>> from vector2d_v3 import Vector2d
>>> Vector([7, 8]) == Vector2d(7, 8)
True
>>> v1 == (1, 2, 3)
False
>>> v2d = Vector2d(1, 2)
>>> v1 + v2d
Vector([4.0, 6.0, 5.0])
Tests of ``+`` with mixed types, swapped operands::
>>> (10, 20, 30) + v1
Vector([13.0, 24.0, 35.0])
>>> from vector2d_v3 import Vector2d
>>> v2d = Vector2d(1, 2)
>>> v2d + v1
Vector([4.0, 6.0, 5.0])
Tests of ``+`` with an unsuitable operand:
>>> v1 + 1
Traceback (most recent call last):
...
TypeError: unsupported operand type(s) for +: 'Vector' and 'int'
>>> v1 + 'ABC'
Traceback (most recent call last):
...
TypeError: unsupported operand type(s) for +: 'Vector' and 'str'
"""
from array import array
@@ -227,14 +257,9 @@ class Vector:
return (bytes([ord(self.typecode)]) +
bytes(self._components))
# BEGIN VECTOR_V6_EQ
def __eq__(self, other):
if isinstance(other, Vector):
return (len(self) == len(other) and
all(a == b for a, b in zip(self, other)))
else:
return NotImplemented
# END VECTOR_V6_EQ
return (len(self) == len(other) and
all(a == b for a, b in zip(self, other)))
def __hash__(self):
hashes = (hash(x) for x in self)
@@ -299,10 +324,14 @@ class Vector:
memv = memoryview(octets[1:]).cast(typecode)
return cls(memv)
# BEGIN VECTOR_V6
def __add__(self, other):
if len(self) != len(other):
cls_name = type(self).__name__
msg = 'cannot add {!r} of different dimensions'
raise ValueError(msg.format(cls_name))
return Vector(a + b for a, b in zip(self, other))
try:
pairs = itertools.zip_longest(self, other, fillvalue=0.0)
return Vector(a + b for a, b in pairs)
except TypeError:
return NotImplemented
def __radd__(self, other):
return self + other
# END VECTOR_V6