added chapter map to README
This commit is contained in:
4
16-op-overloading/README.rst
Normal file
4
16-op-overloading/README.rst
Normal file
@@ -0,0 +1,4 @@
|
||||
Sample code for Chapter 13 - "Operator overloading: doing it right"
|
||||
|
||||
From the book "Fluent Python" by Luciano Ramalho (O'Reilly, 2015)
|
||||
http://shop.oreilly.com/product/0636920032519.do
|
||||
28
16-op-overloading/bingo.py
Normal file
28
16-op-overloading/bingo.py
Normal file
@@ -0,0 +1,28 @@
|
||||
# BEGIN TOMBOLA_BINGO
|
||||
|
||||
import random
|
||||
|
||||
from tombola import Tombola
|
||||
|
||||
|
||||
class BingoCage(Tombola): # <1>
|
||||
|
||||
def __init__(self, items):
|
||||
self._randomizer = random.SystemRandom() # <2>
|
||||
self._items = []
|
||||
self.load(items) # <3>
|
||||
|
||||
def load(self, items):
|
||||
self._items.extend(items)
|
||||
self._randomizer.shuffle(self._items) # <4>
|
||||
|
||||
def pick(self): # <5>
|
||||
try:
|
||||
return self._items.pop()
|
||||
except IndexError:
|
||||
raise LookupError('pick from empty BingoCage')
|
||||
|
||||
def __call__(self): # <7>
|
||||
self.pick()
|
||||
|
||||
# END TOMBOLA_BINGO
|
||||
86
16-op-overloading/bingoaddable.py
Normal file
86
16-op-overloading/bingoaddable.py
Normal file
@@ -0,0 +1,86 @@
|
||||
"""
|
||||
======================
|
||||
AddableBingoCage tests
|
||||
======================
|
||||
|
||||
|
||||
Tests for __add__:
|
||||
|
||||
# BEGIN ADDABLE_BINGO_ADD_DEMO
|
||||
|
||||
>>> vowels = 'AEIOU'
|
||||
>>> globe = AddableBingoCage(vowels) # <1>
|
||||
>>> globe.inspect()
|
||||
('A', 'E', 'I', 'O', 'U')
|
||||
>>> globe.pick() in vowels # <2>
|
||||
True
|
||||
>>> len(globe.inspect()) # <3>
|
||||
4
|
||||
>>> globe2 = AddableBingoCage('XYZ') # <4>
|
||||
>>> globe3 = globe + globe2
|
||||
>>> len(globe3.inspect()) # <5>
|
||||
7
|
||||
>>> void = globe + [10, 20] # <6>
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
TypeError: unsupported operand type(s) for +: 'AddableBingoCage' and 'list'
|
||||
|
||||
|
||||
# END ADDABLE_BINGO_ADD_DEMO
|
||||
|
||||
Tests for __iadd__:
|
||||
|
||||
# BEGIN ADDABLE_BINGO_IADD_DEMO
|
||||
|
||||
>>> globe_orig = globe # <1>
|
||||
>>> len(globe.inspect()) # <2>
|
||||
4
|
||||
>>> globe += globe2 # <3>
|
||||
>>> len(globe.inspect())
|
||||
7
|
||||
>>> globe += ['M', 'N'] # <4>
|
||||
>>> len(globe.inspect())
|
||||
9
|
||||
>>> globe is globe_orig # <5>
|
||||
True
|
||||
>>> globe += 1 # <6>
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
TypeError: right operand in += must be 'AddableBingoCage' or an iterable
|
||||
|
||||
# END ADDABLE_BINGO_IADD_DEMO
|
||||
|
||||
"""
|
||||
|
||||
# BEGIN ADDABLE_BINGO
|
||||
import itertools # <1>
|
||||
|
||||
from tombola import Tombola
|
||||
from bingo import BingoCage
|
||||
|
||||
|
||||
class AddableBingoCage(BingoCage): # <2>
|
||||
|
||||
def __add__(self, other):
|
||||
if isinstance(other, Tombola): # <3>
|
||||
return AddableBingoCage(self.inspect() + other.inspect()) # <6>
|
||||
else:
|
||||
return NotImplemented
|
||||
|
||||
def __iadd__(self, other):
|
||||
if isinstance(other, Tombola):
|
||||
other_iterable = other.inspect() # <4>
|
||||
else:
|
||||
try:
|
||||
other_iterable = iter(other) # <5>
|
||||
except TypeError: # <6>
|
||||
self_cls = type(self).__name__
|
||||
msg = "right operand in += must be {!r} or an iterable"
|
||||
raise TypeError(msg.format(self_cls))
|
||||
self.load(other_iterable) # <7>
|
||||
return self # <8>
|
||||
|
||||
|
||||
|
||||
|
||||
# END ADDABLE_BINGO
|
||||
35
16-op-overloading/tombola.py
Normal file
35
16-op-overloading/tombola.py
Normal file
@@ -0,0 +1,35 @@
|
||||
# BEGIN TOMBOLA_ABC
|
||||
|
||||
import abc
|
||||
|
||||
class Tombola(abc.ABC): # <1>
|
||||
|
||||
@abc.abstractmethod
|
||||
def load(self, iterable): # <2>
|
||||
"""Add items from an iterable."""
|
||||
|
||||
@abc.abstractmethod
|
||||
def pick(self): # <3>
|
||||
"""Remove item at random, returning it.
|
||||
|
||||
This method should raise `LookupError` when the instance is empty.
|
||||
"""
|
||||
|
||||
def loaded(self): # <4>
|
||||
"""Return `True` if there's at least 1 item, `False` otherwise."""
|
||||
return bool(self.inspect()) # <5>
|
||||
|
||||
|
||||
def inspect(self):
|
||||
"""Return a sorted tuple with the items currently inside."""
|
||||
items = []
|
||||
while True: # <6>
|
||||
try:
|
||||
items.append(self.pick())
|
||||
except LookupError:
|
||||
break
|
||||
self.load(items) # <7>
|
||||
return tuple(sorted(items))
|
||||
|
||||
|
||||
# END TOMBOLA_ABC
|
||||
35
16-op-overloading/unary_plus_decimal.py
Normal file
35
16-op-overloading/unary_plus_decimal.py
Normal file
@@ -0,0 +1,35 @@
|
||||
"""
|
||||
# BEGIN UNARY_PLUS_DECIMAL
|
||||
|
||||
>>> import decimal
|
||||
>>> ctx = decimal.getcontext() # <1>
|
||||
>>> ctx.prec = 40 # <2>
|
||||
>>> one_third = decimal.Decimal('1') / decimal.Decimal('3') # <3>
|
||||
>>> one_third # <4>
|
||||
Decimal('0.3333333333333333333333333333333333333333')
|
||||
>>> one_third == +one_third # <5>
|
||||
True
|
||||
>>> ctx.prec = 28 # <6>
|
||||
>>> one_third == +one_third # <7>
|
||||
False
|
||||
>>> +one_third # <8>
|
||||
Decimal('0.3333333333333333333333333333')
|
||||
|
||||
# END UNARY_PLUS_DECIMAL
|
||||
|
||||
"""
|
||||
|
||||
import decimal
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
with decimal.localcontext() as ctx:
|
||||
ctx.prec = 40
|
||||
print('precision:', ctx.prec)
|
||||
one_third = decimal.Decimal('1') / decimal.Decimal('3')
|
||||
print(' one_third:', one_third)
|
||||
print(' +one_third:', +one_third)
|
||||
|
||||
print('precision:', decimal.getcontext().prec)
|
||||
print(' one_third:', one_third)
|
||||
print(' +one_third:', +one_third)
|
||||
151
16-op-overloading/vector2d_v3.py
Normal file
151
16-op-overloading/vector2d_v3.py
Normal file
@@ -0,0 +1,151 @@
|
||||
"""
|
||||
A 2-dimensional vector class
|
||||
|
||||
>>> v1 = Vector2d(3, 4)
|
||||
>>> print(v1.x, v1.y)
|
||||
3.0 4.0
|
||||
>>> x, y = v1
|
||||
>>> x, y
|
||||
(3.0, 4.0)
|
||||
>>> v1
|
||||
Vector2d(3.0, 4.0)
|
||||
>>> v1_clone = eval(repr(v1))
|
||||
>>> v1 == v1_clone
|
||||
True
|
||||
>>> print(v1)
|
||||
(3.0, 4.0)
|
||||
>>> octets = bytes(v1)
|
||||
>>> octets
|
||||
b'd\\x00\\x00\\x00\\x00\\x00\\x00\\x08@\\x00\\x00\\x00\\x00\\x00\\x00\\x10@'
|
||||
>>> abs(v1)
|
||||
5.0
|
||||
>>> bool(v1), bool(Vector2d(0, 0))
|
||||
(True, False)
|
||||
|
||||
|
||||
Test of ``.frombytes()`` class method:
|
||||
|
||||
>>> v1_clone = Vector2d.frombytes(bytes(v1))
|
||||
>>> v1_clone
|
||||
Vector2d(3.0, 4.0)
|
||||
>>> v1 == v1_clone
|
||||
True
|
||||
|
||||
|
||||
Tests of ``format()`` with Cartesian coordinates:
|
||||
|
||||
>>> format(v1)
|
||||
'(3.0, 4.0)'
|
||||
>>> format(v1, '.2f')
|
||||
'(3.00, 4.00)'
|
||||
>>> format(v1, '.3e')
|
||||
'(3.000e+00, 4.000e+00)'
|
||||
|
||||
|
||||
Tests of the ``angle`` method::
|
||||
|
||||
>>> Vector2d(0, 0).angle()
|
||||
0.0
|
||||
>>> Vector2d(1, 0).angle()
|
||||
0.0
|
||||
>>> epsilon = 10**-8
|
||||
>>> abs(Vector2d(0, 1).angle() - math.pi/2) < epsilon
|
||||
True
|
||||
>>> abs(Vector2d(1, 1).angle() - math.pi/4) < epsilon
|
||||
True
|
||||
|
||||
|
||||
Tests of ``format()`` with polar coordinates:
|
||||
|
||||
>>> format(Vector2d(1, 1), 'p') # doctest:+ELLIPSIS
|
||||
'<1.414213..., 0.785398...>'
|
||||
>>> format(Vector2d(1, 1), '.3ep')
|
||||
'<1.414e+00, 7.854e-01>'
|
||||
>>> format(Vector2d(1, 1), '0.5fp')
|
||||
'<1.41421, 0.78540>'
|
||||
|
||||
|
||||
Tests of `x` and `y` read-only properties:
|
||||
|
||||
>>> v1.x, v1.y
|
||||
(3.0, 4.0)
|
||||
>>> v1.x = 123
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
AttributeError: can't set attribute
|
||||
|
||||
|
||||
Tests of hashing:
|
||||
|
||||
>>> v1 = Vector2d(3, 4)
|
||||
>>> v2 = Vector2d(3.1, 4.2)
|
||||
>>> hash(v1), hash(v2)
|
||||
(7, 384307168202284039)
|
||||
>>> len(set([v1, v2]))
|
||||
2
|
||||
|
||||
"""
|
||||
|
||||
from array import array
|
||||
import math
|
||||
|
||||
class Vector2d:
|
||||
typecode = 'd'
|
||||
|
||||
def __init__(self, x, y):
|
||||
self.__x = float(x)
|
||||
self.__y = float(y)
|
||||
|
||||
@property
|
||||
def x(self):
|
||||
return self.__x
|
||||
|
||||
@property
|
||||
def y(self):
|
||||
return self.__y
|
||||
|
||||
def __iter__(self):
|
||||
return (i for i in (self.x, self.y))
|
||||
|
||||
def __repr__(self):
|
||||
class_name = type(self).__name__
|
||||
return '{}({!r}, {!r})'.format(class_name, *self)
|
||||
|
||||
def __str__(self):
|
||||
return str(tuple(self))
|
||||
|
||||
def __bytes__(self):
|
||||
return (bytes([ord(self.typecode)]) +
|
||||
bytes(array(self.typecode, self)))
|
||||
|
||||
def __eq__(self, other):
|
||||
return tuple(self) == tuple(other)
|
||||
|
||||
def __hash__(self):
|
||||
return hash(self.x) ^ hash(self.y)
|
||||
|
||||
def __abs__(self):
|
||||
return math.hypot(self.x, self.y)
|
||||
|
||||
def __bool__(self):
|
||||
return bool(abs(self))
|
||||
|
||||
def angle(self):
|
||||
return math.atan2(self.y, self.x)
|
||||
|
||||
def __format__(self, fmt_spec=''):
|
||||
if fmt_spec.endswith('p'):
|
||||
fmt_spec = fmt_spec[:-1]
|
||||
coords = (abs(self), self.angle())
|
||||
outer_fmt = '<{}, {}>'
|
||||
else:
|
||||
coords = self
|
||||
outer_fmt = '({}, {})'
|
||||
components = (format(c, fmt_spec) for c in coords)
|
||||
return outer_fmt.format(*components)
|
||||
|
||||
@classmethod
|
||||
def frombytes(cls, octets):
|
||||
typecode = chr(octets[0])
|
||||
memv = memoryview(octets[1:]).cast(typecode)
|
||||
return cls(*memv)
|
||||
431
16-op-overloading/vector_py3_5.py
Normal file
431
16-op-overloading/vector_py3_5.py
Normal file
@@ -0,0 +1,431 @@
|
||||
"""
|
||||
A multi-dimensional ``Vector`` class, take 9: operator ``@``
|
||||
|
||||
WARNING: This example requires Python 3.5 or later.
|
||||
|
||||
A ``Vector`` is built from an iterable of numbers::
|
||||
|
||||
>>> Vector([3.1, 4.2])
|
||||
Vector([3.1, 4.2])
|
||||
>>> Vector((3, 4, 5))
|
||||
Vector([3.0, 4.0, 5.0])
|
||||
>>> Vector(range(10))
|
||||
Vector([0.0, 1.0, 2.0, 3.0, 4.0, ...])
|
||||
|
||||
|
||||
Tests with 2-dimensions (same results as ``vector2d_v1.py``)::
|
||||
|
||||
>>> v1 = Vector([3, 4])
|
||||
>>> x, y = v1
|
||||
>>> x, y
|
||||
(3.0, 4.0)
|
||||
>>> v1
|
||||
Vector([3.0, 4.0])
|
||||
>>> v1_clone = eval(repr(v1))
|
||||
>>> v1 == v1_clone
|
||||
True
|
||||
>>> print(v1)
|
||||
(3.0, 4.0)
|
||||
>>> octets = bytes(v1)
|
||||
>>> octets
|
||||
b'd\\x00\\x00\\x00\\x00\\x00\\x00\\x08@\\x00\\x00\\x00\\x00\\x00\\x00\\x10@'
|
||||
>>> abs(v1)
|
||||
5.0
|
||||
>>> bool(v1), bool(Vector([0, 0]))
|
||||
(True, False)
|
||||
|
||||
|
||||
Test of ``.frombytes()`` class method:
|
||||
|
||||
>>> v1_clone = Vector.frombytes(bytes(v1))
|
||||
>>> v1_clone
|
||||
Vector([3.0, 4.0])
|
||||
>>> v1 == v1_clone
|
||||
True
|
||||
|
||||
|
||||
Tests with 3-dimensions::
|
||||
|
||||
>>> v1 = Vector([3, 4, 5])
|
||||
>>> x, y, z = v1
|
||||
>>> x, y, z
|
||||
(3.0, 4.0, 5.0)
|
||||
>>> v1
|
||||
Vector([3.0, 4.0, 5.0])
|
||||
>>> v1_clone = eval(repr(v1))
|
||||
>>> v1 == v1_clone
|
||||
True
|
||||
>>> print(v1)
|
||||
(3.0, 4.0, 5.0)
|
||||
>>> abs(v1) # doctest:+ELLIPSIS
|
||||
7.071067811...
|
||||
>>> bool(v1), bool(Vector([0, 0, 0]))
|
||||
(True, False)
|
||||
|
||||
|
||||
Tests with many dimensions::
|
||||
|
||||
>>> v7 = Vector(range(7))
|
||||
>>> v7
|
||||
Vector([0.0, 1.0, 2.0, 3.0, 4.0, ...])
|
||||
>>> abs(v7) # doctest:+ELLIPSIS
|
||||
9.53939201...
|
||||
|
||||
|
||||
Test of ``.__bytes__`` and ``.frombytes()`` methods::
|
||||
|
||||
>>> v1 = Vector([3, 4, 5])
|
||||
>>> v1_clone = Vector.frombytes(bytes(v1))
|
||||
>>> v1_clone
|
||||
Vector([3.0, 4.0, 5.0])
|
||||
>>> v1 == v1_clone
|
||||
True
|
||||
|
||||
|
||||
Tests of sequence behavior::
|
||||
|
||||
>>> v1 = Vector([3, 4, 5])
|
||||
>>> len(v1)
|
||||
3
|
||||
>>> v1[0], v1[len(v1)-1], v1[-1]
|
||||
(3.0, 5.0, 5.0)
|
||||
|
||||
|
||||
Test of slicing::
|
||||
|
||||
>>> v7 = Vector(range(7))
|
||||
>>> v7[-1]
|
||||
6.0
|
||||
>>> v7[1:4]
|
||||
Vector([1.0, 2.0, 3.0])
|
||||
>>> v7[-1:]
|
||||
Vector([6.0])
|
||||
>>> v7[1,2]
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
TypeError: Vector indices must be integers
|
||||
|
||||
|
||||
Tests of dynamic attribute access::
|
||||
|
||||
>>> v7 = Vector(range(10))
|
||||
>>> v7.x
|
||||
0.0
|
||||
>>> v7.y, v7.z, v7.t
|
||||
(1.0, 2.0, 3.0)
|
||||
|
||||
Dynamic attribute lookup failures::
|
||||
|
||||
>>> v7.k
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
AttributeError: 'Vector' object has no attribute 'k'
|
||||
>>> v3 = Vector(range(3))
|
||||
>>> v3.t
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
AttributeError: 'Vector' object has no attribute 't'
|
||||
>>> v3.spam
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
AttributeError: 'Vector' object has no attribute 'spam'
|
||||
|
||||
|
||||
Tests of hashing::
|
||||
|
||||
>>> v1 = Vector([3, 4])
|
||||
>>> v2 = Vector([3.1, 4.2])
|
||||
>>> v3 = Vector([3, 4, 5])
|
||||
>>> v6 = Vector(range(6))
|
||||
>>> hash(v1), hash(v3), hash(v6)
|
||||
(7, 2, 1)
|
||||
|
||||
|
||||
Most hash values of non-integers vary from a 32-bit to 64-bit Python build::
|
||||
|
||||
>>> import sys
|
||||
>>> hash(v2) == (384307168202284039 if sys.maxsize > 2**32 else 357915986)
|
||||
True
|
||||
|
||||
|
||||
Tests of ``format()`` with Cartesian coordinates in 2D::
|
||||
|
||||
>>> v1 = Vector([3, 4])
|
||||
>>> format(v1)
|
||||
'(3.0, 4.0)'
|
||||
>>> format(v1, '.2f')
|
||||
'(3.00, 4.00)'
|
||||
>>> format(v1, '.3e')
|
||||
'(3.000e+00, 4.000e+00)'
|
||||
|
||||
|
||||
Tests of ``format()`` with Cartesian coordinates in 3D and 7D::
|
||||
|
||||
>>> v3 = Vector([3, 4, 5])
|
||||
>>> format(v3)
|
||||
'(3.0, 4.0, 5.0)'
|
||||
>>> format(Vector(range(7)))
|
||||
'(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0)'
|
||||
|
||||
|
||||
Tests of ``format()`` with spherical coordinates in 2D, 3D and 4D::
|
||||
|
||||
>>> format(Vector([1, 1]), 'h') # doctest:+ELLIPSIS
|
||||
'<1.414213..., 0.785398...>'
|
||||
>>> format(Vector([1, 1]), '.3eh')
|
||||
'<1.414e+00, 7.854e-01>'
|
||||
>>> format(Vector([1, 1]), '0.5fh')
|
||||
'<1.41421, 0.78540>'
|
||||
>>> format(Vector([1, 1, 1]), 'h') # doctest:+ELLIPSIS
|
||||
'<1.73205..., 0.95531..., 0.78539...>'
|
||||
>>> format(Vector([2, 2, 2]), '.3eh')
|
||||
'<3.464e+00, 9.553e-01, 7.854e-01>'
|
||||
>>> format(Vector([0, 0, 0]), '0.5fh')
|
||||
'<0.00000, 0.00000, 0.00000>'
|
||||
>>> format(Vector([-1, -1, -1, -1]), 'h') # doctest:+ELLIPSIS
|
||||
'<2.0, 2.09439..., 2.18627..., 3.92699...>'
|
||||
>>> format(Vector([2, 2, 2, 2]), '.3eh')
|
||||
'<4.000e+00, 1.047e+00, 9.553e-01, 7.854e-01>'
|
||||
>>> format(Vector([0, 1, 0, 0]), '0.5fh')
|
||||
'<1.00000, 1.57080, 0.00000, 0.00000>'
|
||||
|
||||
|
||||
Basic tests of operator ``+``::
|
||||
|
||||
>>> 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
|
||||
>>> 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'
|
||||
|
||||
|
||||
Basic tests of operator ``*``::
|
||||
|
||||
>>> v1 = Vector([1, 2, 3])
|
||||
>>> v1 * 10
|
||||
Vector([10.0, 20.0, 30.0])
|
||||
>>> 10 * v1
|
||||
Vector([10.0, 20.0, 30.0])
|
||||
|
||||
|
||||
Tests of ``*`` with unusual but valid operands::
|
||||
|
||||
>>> v1 * True
|
||||
Vector([1.0, 2.0, 3.0])
|
||||
>>> from fractions import Fraction
|
||||
>>> v1 * Fraction(1, 3) # doctest:+ELLIPSIS
|
||||
Vector([0.3333..., 0.6666..., 1.0])
|
||||
|
||||
|
||||
Tests of ``*`` with unsuitable operands::
|
||||
|
||||
>>> v1 * (1, 2)
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
TypeError: can't multiply sequence by non-int of type 'Vector'
|
||||
|
||||
|
||||
Tests of operator `==`::
|
||||
|
||||
>>> va = Vector(range(1, 4))
|
||||
>>> vb = Vector([1.0, 2.0, 3.0])
|
||||
>>> va == vb
|
||||
True
|
||||
>>> vc = Vector([1, 2])
|
||||
>>> from vector2d_v3 import Vector2d
|
||||
>>> v2d = Vector2d(1, 2)
|
||||
>>> vc == v2d
|
||||
True
|
||||
>>> va == (1, 2, 3)
|
||||
False
|
||||
|
||||
|
||||
Tests of operator `!=`::
|
||||
|
||||
>>> va != vb
|
||||
False
|
||||
>>> vc != v2d
|
||||
False
|
||||
>>> va != (1, 2, 3)
|
||||
True
|
||||
|
||||
|
||||
Tests for operator `@` (Python >= 3.5), computing the dot product::
|
||||
|
||||
>>> va = Vector([1, 2, 3])
|
||||
>>> vz = Vector([5, 6, 7])
|
||||
>>> va @ vz == 38.0 # 1*5 + 2*6 + 3*7
|
||||
True
|
||||
>>> [10, 20, 30] @ vz
|
||||
380.0
|
||||
>>> va @ 3
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
TypeError: unsupported operand type(s) for @: 'Vector' and 'int'
|
||||
|
||||
|
||||
"""
|
||||
|
||||
from array import array
|
||||
import reprlib
|
||||
import math
|
||||
import functools
|
||||
import operator
|
||||
import itertools
|
||||
import numbers
|
||||
|
||||
|
||||
class Vector:
|
||||
typecode = 'd'
|
||||
|
||||
def __init__(self, components):
|
||||
self._components = array(self.typecode, components)
|
||||
|
||||
def __iter__(self):
|
||||
return iter(self._components)
|
||||
|
||||
def __repr__(self):
|
||||
components = reprlib.repr(self._components)
|
||||
components = components[components.find('['):-1]
|
||||
return 'Vector({})'.format(components)
|
||||
|
||||
def __str__(self):
|
||||
return str(tuple(self))
|
||||
|
||||
def __bytes__(self):
|
||||
return (bytes([ord(self.typecode)]) +
|
||||
bytes(self._components))
|
||||
|
||||
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
|
||||
|
||||
def __hash__(self):
|
||||
hashes = (hash(x) for x in self)
|
||||
return functools.reduce(operator.xor, hashes, 0)
|
||||
|
||||
def __abs__(self):
|
||||
return math.sqrt(sum(x * x for x in self))
|
||||
|
||||
def __bool__(self):
|
||||
return bool(abs(self))
|
||||
|
||||
def __len__(self):
|
||||
return len(self._components)
|
||||
|
||||
def __getitem__(self, index):
|
||||
cls = type(self)
|
||||
if isinstance(index, slice):
|
||||
return cls(self._components[index])
|
||||
elif isinstance(index, int):
|
||||
return self._components[index]
|
||||
else:
|
||||
msg = '{.__name__} indices must be integers'
|
||||
raise TypeError(msg.format(cls))
|
||||
|
||||
shortcut_names = 'xyzt'
|
||||
|
||||
def __getattr__(self, name):
|
||||
cls = type(self)
|
||||
if len(name) == 1:
|
||||
pos = cls.shortcut_names.find(name)
|
||||
if 0 <= pos < len(self._components):
|
||||
return self._components[pos]
|
||||
msg = '{.__name__!r} object has no attribute {!r}'
|
||||
raise AttributeError(msg.format(cls, name))
|
||||
|
||||
def angle(self, n):
|
||||
r = math.sqrt(sum(x * x for x in self[n:]))
|
||||
a = math.atan2(r, self[n-1])
|
||||
if (n == len(self) - 1) and (self[-1] < 0):
|
||||
return math.pi * 2 - a
|
||||
else:
|
||||
return a
|
||||
|
||||
def angles(self):
|
||||
return (self.angle(n) for n in range(1, len(self)))
|
||||
|
||||
def __format__(self, fmt_spec=''):
|
||||
if fmt_spec.endswith('h'): # hyperspherical coordinates
|
||||
fmt_spec = fmt_spec[:-1]
|
||||
coords = itertools.chain([abs(self)],
|
||||
self.angles())
|
||||
outer_fmt = '<{}>'
|
||||
else:
|
||||
coords = self
|
||||
outer_fmt = '({})'
|
||||
components = (format(c, fmt_spec) for c in coords)
|
||||
return outer_fmt.format(', '.join(components))
|
||||
|
||||
@classmethod
|
||||
def frombytes(cls, octets):
|
||||
typecode = chr(octets[0])
|
||||
memv = memoryview(octets[1:]).cast(typecode)
|
||||
return cls(memv)
|
||||
|
||||
def __add__(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
|
||||
|
||||
def __mul__(self, scalar):
|
||||
if isinstance(scalar, numbers.Real):
|
||||
return Vector(n * scalar for n in self)
|
||||
else:
|
||||
return NotImplemented
|
||||
|
||||
def __rmul__(self, scalar):
|
||||
return self * scalar
|
||||
|
||||
def __matmul__(self, other):
|
||||
try:
|
||||
return sum(a * b for a, b in zip(self, other))
|
||||
except TypeError:
|
||||
return NotImplemented
|
||||
|
||||
def __rmatmul__(self, other):
|
||||
return self @ other # this only works in Python 3.5
|
||||
362
16-op-overloading/vector_v6.py
Normal file
362
16-op-overloading/vector_v6.py
Normal file
@@ -0,0 +1,362 @@
|
||||
"""
|
||||
A multi-dimensional ``Vector`` class, take 6: operator ``+``
|
||||
|
||||
A ``Vector`` is built from an iterable of numbers::
|
||||
|
||||
>>> Vector([3.1, 4.2])
|
||||
Vector([3.1, 4.2])
|
||||
>>> Vector((3, 4, 5))
|
||||
Vector([3.0, 4.0, 5.0])
|
||||
>>> Vector(range(10))
|
||||
Vector([0.0, 1.0, 2.0, 3.0, 4.0, ...])
|
||||
|
||||
|
||||
Tests with 2-dimensions (same results as ``vector2d_v1.py``)::
|
||||
|
||||
>>> v1 = Vector([3, 4])
|
||||
>>> x, y = v1
|
||||
>>> x, y
|
||||
(3.0, 4.0)
|
||||
>>> v1
|
||||
Vector([3.0, 4.0])
|
||||
>>> v1_clone = eval(repr(v1))
|
||||
>>> v1 == v1_clone
|
||||
True
|
||||
>>> print(v1)
|
||||
(3.0, 4.0)
|
||||
>>> octets = bytes(v1)
|
||||
>>> octets
|
||||
b'd\\x00\\x00\\x00\\x00\\x00\\x00\\x08@\\x00\\x00\\x00\\x00\\x00\\x00\\x10@'
|
||||
>>> abs(v1)
|
||||
5.0
|
||||
>>> bool(v1), bool(Vector([0, 0]))
|
||||
(True, False)
|
||||
|
||||
|
||||
Test of ``.frombytes()`` class method:
|
||||
|
||||
>>> v1_clone = Vector.frombytes(bytes(v1))
|
||||
>>> v1_clone
|
||||
Vector([3.0, 4.0])
|
||||
>>> v1 == v1_clone
|
||||
True
|
||||
|
||||
|
||||
Tests with 3-dimensions::
|
||||
|
||||
>>> v1 = Vector([3, 4, 5])
|
||||
>>> x, y, z = v1
|
||||
>>> x, y, z
|
||||
(3.0, 4.0, 5.0)
|
||||
>>> v1
|
||||
Vector([3.0, 4.0, 5.0])
|
||||
>>> v1_clone = eval(repr(v1))
|
||||
>>> v1 == v1_clone
|
||||
True
|
||||
>>> print(v1)
|
||||
(3.0, 4.0, 5.0)
|
||||
>>> abs(v1) # doctest:+ELLIPSIS
|
||||
7.071067811...
|
||||
>>> bool(v1), bool(Vector([0, 0, 0]))
|
||||
(True, False)
|
||||
|
||||
|
||||
Tests with many dimensions::
|
||||
|
||||
>>> v7 = Vector(range(7))
|
||||
>>> v7
|
||||
Vector([0.0, 1.0, 2.0, 3.0, 4.0, ...])
|
||||
>>> abs(v7) # doctest:+ELLIPSIS
|
||||
9.53939201...
|
||||
|
||||
|
||||
Test of ``.__bytes__`` and ``.frombytes()`` methods::
|
||||
|
||||
>>> v1 = Vector([3, 4, 5])
|
||||
>>> v1_clone = Vector.frombytes(bytes(v1))
|
||||
>>> v1_clone
|
||||
Vector([3.0, 4.0, 5.0])
|
||||
>>> v1 == v1_clone
|
||||
True
|
||||
|
||||
|
||||
Tests of sequence behavior::
|
||||
|
||||
>>> v1 = Vector([3, 4, 5])
|
||||
>>> len(v1)
|
||||
3
|
||||
>>> v1[0], v1[len(v1)-1], v1[-1]
|
||||
(3.0, 5.0, 5.0)
|
||||
|
||||
|
||||
Test of slicing::
|
||||
|
||||
>>> v7 = Vector(range(7))
|
||||
>>> v7[-1]
|
||||
6.0
|
||||
>>> v7[1:4]
|
||||
Vector([1.0, 2.0, 3.0])
|
||||
>>> v7[-1:]
|
||||
Vector([6.0])
|
||||
>>> v7[1,2]
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
TypeError: Vector indices must be integers
|
||||
|
||||
|
||||
Tests of dynamic attribute access::
|
||||
|
||||
>>> v7 = Vector(range(10))
|
||||
>>> v7.x
|
||||
0.0
|
||||
>>> v7.y, v7.z, v7.t
|
||||
(1.0, 2.0, 3.0)
|
||||
|
||||
Dynamic attribute lookup failures::
|
||||
|
||||
>>> v7.k
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
AttributeError: 'Vector' object has no attribute 'k'
|
||||
>>> v3 = Vector(range(3))
|
||||
>>> v3.t
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
AttributeError: 'Vector' object has no attribute 't'
|
||||
>>> v3.spam
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
AttributeError: 'Vector' object has no attribute 'spam'
|
||||
|
||||
|
||||
Tests of hashing::
|
||||
|
||||
>>> v1 = Vector([3, 4])
|
||||
>>> v2 = Vector([3.1, 4.2])
|
||||
>>> v3 = Vector([3, 4, 5])
|
||||
>>> v6 = Vector(range(6))
|
||||
>>> hash(v1), hash(v3), hash(v6)
|
||||
(7, 2, 1)
|
||||
|
||||
|
||||
Most hash values of non-integers vary from a 32-bit to 64-bit Python build::
|
||||
|
||||
>>> import sys
|
||||
>>> hash(v2) == (384307168202284039 if sys.maxsize > 2**32 else 357915986)
|
||||
True
|
||||
|
||||
|
||||
Tests of ``format()`` with Cartesian coordinates in 2D::
|
||||
|
||||
>>> v1 = Vector([3, 4])
|
||||
>>> format(v1)
|
||||
'(3.0, 4.0)'
|
||||
>>> format(v1, '.2f')
|
||||
'(3.00, 4.00)'
|
||||
>>> format(v1, '.3e')
|
||||
'(3.000e+00, 4.000e+00)'
|
||||
|
||||
|
||||
Tests of ``format()`` with Cartesian coordinates in 3D and 7D::
|
||||
|
||||
>>> v3 = Vector([3, 4, 5])
|
||||
>>> format(v3)
|
||||
'(3.0, 4.0, 5.0)'
|
||||
>>> format(Vector(range(7)))
|
||||
'(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0)'
|
||||
|
||||
|
||||
Tests of ``format()`` with spherical coordinates in 2D, 3D and 4D::
|
||||
|
||||
>>> format(Vector([1, 1]), 'h') # doctest:+ELLIPSIS
|
||||
'<1.414213..., 0.785398...>'
|
||||
>>> format(Vector([1, 1]), '.3eh')
|
||||
'<1.414e+00, 7.854e-01>'
|
||||
>>> format(Vector([1, 1]), '0.5fh')
|
||||
'<1.41421, 0.78540>'
|
||||
>>> format(Vector([1, 1, 1]), 'h') # doctest:+ELLIPSIS
|
||||
'<1.73205..., 0.95531..., 0.78539...>'
|
||||
>>> format(Vector([2, 2, 2]), '.3eh')
|
||||
'<3.464e+00, 9.553e-01, 7.854e-01>'
|
||||
>>> format(Vector([0, 0, 0]), '0.5fh')
|
||||
'<0.00000, 0.00000, 0.00000>'
|
||||
>>> format(Vector([-1, -1, -1, -1]), 'h') # doctest:+ELLIPSIS
|
||||
'<2.0, 2.09439..., 2.18627..., 3.92699...>'
|
||||
>>> format(Vector([2, 2, 2, 2]), '.3eh')
|
||||
'<4.000e+00, 1.047e+00, 9.553e-01, 7.854e-01>'
|
||||
>>> format(Vector([0, 1, 0, 0]), '0.5fh')
|
||||
'<1.00000, 1.57080, 0.00000, 0.00000>'
|
||||
|
||||
|
||||
Unary operator tests::
|
||||
|
||||
>>> v1 = Vector([3, 4])
|
||||
>>> abs(v1)
|
||||
5.0
|
||||
>>> -v1
|
||||
Vector([-3.0, -4.0])
|
||||
>>> +v1
|
||||
Vector([3.0, 4.0])
|
||||
|
||||
|
||||
Basic tests of operator ``+``::
|
||||
|
||||
>>> 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
|
||||
>>> 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
|
||||
import reprlib
|
||||
import math
|
||||
import numbers
|
||||
import functools
|
||||
import operator
|
||||
import itertools
|
||||
|
||||
|
||||
class Vector:
|
||||
typecode = 'd'
|
||||
|
||||
def __init__(self, components):
|
||||
self._components = array(self.typecode, components)
|
||||
|
||||
def __iter__(self):
|
||||
return iter(self._components)
|
||||
|
||||
def __repr__(self):
|
||||
components = reprlib.repr(self._components)
|
||||
components = components[components.find('['):-1]
|
||||
return 'Vector({})'.format(components)
|
||||
|
||||
def __str__(self):
|
||||
return str(tuple(self))
|
||||
|
||||
def __bytes__(self):
|
||||
return (bytes([ord(self.typecode)]) +
|
||||
bytes(self._components))
|
||||
|
||||
def __eq__(self, other):
|
||||
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)
|
||||
return functools.reduce(operator.xor, hashes, 0)
|
||||
|
||||
# BEGIN VECTOR_V6_UNARY
|
||||
def __abs__(self):
|
||||
return math.sqrt(sum(x * x for x in self))
|
||||
|
||||
def __neg__(self):
|
||||
return Vector(-x for x in self) # <1>
|
||||
|
||||
def __pos__(self):
|
||||
return Vector(self) # <2>
|
||||
# END VECTOR_V6_UNARY
|
||||
|
||||
def __bool__(self):
|
||||
return bool(abs(self))
|
||||
|
||||
def __len__(self):
|
||||
return len(self._components)
|
||||
|
||||
def __getitem__(self, index):
|
||||
cls = type(self)
|
||||
if isinstance(index, slice):
|
||||
return cls(self._components[index])
|
||||
elif isinstance(index, numbers.Integral):
|
||||
return self._components[index]
|
||||
else:
|
||||
msg = '{.__name__} indices must be integers'
|
||||
raise TypeError(msg.format(cls))
|
||||
|
||||
shortcut_names = 'xyzt'
|
||||
|
||||
def __getattr__(self, name):
|
||||
cls = type(self)
|
||||
if len(name) == 1:
|
||||
pos = cls.shortcut_names.find(name)
|
||||
if 0 <= pos < len(self._components):
|
||||
return self._components[pos]
|
||||
msg = '{.__name__!r} object has no attribute {!r}'
|
||||
raise AttributeError(msg.format(cls, name))
|
||||
|
||||
def angle(self, n):
|
||||
r = math.sqrt(sum(x * x for x in self[n:]))
|
||||
a = math.atan2(r, self[n-1])
|
||||
if (n == len(self) - 1) and (self[-1] < 0):
|
||||
return math.pi * 2 - a
|
||||
else:
|
||||
return a
|
||||
|
||||
def angles(self):
|
||||
return (self.angle(n) for n in range(1, len(self)))
|
||||
|
||||
def __format__(self, fmt_spec=''):
|
||||
if fmt_spec.endswith('h'): # hyperspherical coordinates
|
||||
fmt_spec = fmt_spec[:-1]
|
||||
coords = itertools.chain([abs(self)],
|
||||
self.angles())
|
||||
outer_fmt = '<{}>'
|
||||
else:
|
||||
coords = self
|
||||
outer_fmt = '({})'
|
||||
components = (format(c, fmt_spec) for c in coords)
|
||||
return outer_fmt.format(', '.join(components))
|
||||
|
||||
@classmethod
|
||||
def frombytes(cls, octets):
|
||||
typecode = chr(octets[0])
|
||||
memv = memoryview(octets[1:]).cast(typecode)
|
||||
return cls(memv)
|
||||
|
||||
# BEGIN VECTOR_V6_ADD
|
||||
def __add__(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_ADD
|
||||
394
16-op-overloading/vector_v7.py
Normal file
394
16-op-overloading/vector_v7.py
Normal file
@@ -0,0 +1,394 @@
|
||||
"""
|
||||
A multi-dimensional ``Vector`` class, take 7: operator ``*``
|
||||
|
||||
A ``Vector`` is built from an iterable of numbers::
|
||||
|
||||
>>> Vector([3.1, 4.2])
|
||||
Vector([3.1, 4.2])
|
||||
>>> Vector((3, 4, 5))
|
||||
Vector([3.0, 4.0, 5.0])
|
||||
>>> Vector(range(10))
|
||||
Vector([0.0, 1.0, 2.0, 3.0, 4.0, ...])
|
||||
|
||||
|
||||
Tests with 2-dimensions (same results as ``vector2d_v1.py``)::
|
||||
|
||||
>>> v1 = Vector([3, 4])
|
||||
>>> x, y = v1
|
||||
>>> x, y
|
||||
(3.0, 4.0)
|
||||
>>> v1
|
||||
Vector([3.0, 4.0])
|
||||
>>> v1_clone = eval(repr(v1))
|
||||
>>> v1 == v1_clone
|
||||
True
|
||||
>>> print(v1)
|
||||
(3.0, 4.0)
|
||||
>>> octets = bytes(v1)
|
||||
>>> octets
|
||||
b'd\\x00\\x00\\x00\\x00\\x00\\x00\\x08@\\x00\\x00\\x00\\x00\\x00\\x00\\x10@'
|
||||
>>> abs(v1)
|
||||
5.0
|
||||
>>> bool(v1), bool(Vector([0, 0]))
|
||||
(True, False)
|
||||
|
||||
|
||||
Test of ``.frombytes()`` class method:
|
||||
|
||||
>>> v1_clone = Vector.frombytes(bytes(v1))
|
||||
>>> v1_clone
|
||||
Vector([3.0, 4.0])
|
||||
>>> v1 == v1_clone
|
||||
True
|
||||
|
||||
|
||||
Tests with 3-dimensions::
|
||||
|
||||
>>> v1 = Vector([3, 4, 5])
|
||||
>>> x, y, z = v1
|
||||
>>> x, y, z
|
||||
(3.0, 4.0, 5.0)
|
||||
>>> v1
|
||||
Vector([3.0, 4.0, 5.0])
|
||||
>>> v1_clone = eval(repr(v1))
|
||||
>>> v1 == v1_clone
|
||||
True
|
||||
>>> print(v1)
|
||||
(3.0, 4.0, 5.0)
|
||||
>>> abs(v1) # doctest:+ELLIPSIS
|
||||
7.071067811...
|
||||
>>> bool(v1), bool(Vector([0, 0, 0]))
|
||||
(True, False)
|
||||
|
||||
|
||||
Tests with many dimensions::
|
||||
|
||||
>>> v7 = Vector(range(7))
|
||||
>>> v7
|
||||
Vector([0.0, 1.0, 2.0, 3.0, 4.0, ...])
|
||||
>>> abs(v7) # doctest:+ELLIPSIS
|
||||
9.53939201...
|
||||
|
||||
|
||||
Test of ``.__bytes__`` and ``.frombytes()`` methods::
|
||||
|
||||
>>> v1 = Vector([3, 4, 5])
|
||||
>>> v1_clone = Vector.frombytes(bytes(v1))
|
||||
>>> v1_clone
|
||||
Vector([3.0, 4.0, 5.0])
|
||||
>>> v1 == v1_clone
|
||||
True
|
||||
|
||||
|
||||
Tests of sequence behavior::
|
||||
|
||||
>>> v1 = Vector([3, 4, 5])
|
||||
>>> len(v1)
|
||||
3
|
||||
>>> v1[0], v1[len(v1)-1], v1[-1]
|
||||
(3.0, 5.0, 5.0)
|
||||
|
||||
|
||||
Test of slicing::
|
||||
|
||||
>>> v7 = Vector(range(7))
|
||||
>>> v7[-1]
|
||||
6.0
|
||||
>>> v7[1:4]
|
||||
Vector([1.0, 2.0, 3.0])
|
||||
>>> v7[-1:]
|
||||
Vector([6.0])
|
||||
>>> v7[1,2]
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
TypeError: Vector indices must be integers
|
||||
|
||||
|
||||
Tests of dynamic attribute access::
|
||||
|
||||
>>> v7 = Vector(range(10))
|
||||
>>> v7.x
|
||||
0.0
|
||||
>>> v7.y, v7.z, v7.t
|
||||
(1.0, 2.0, 3.0)
|
||||
|
||||
Dynamic attribute lookup failures::
|
||||
|
||||
>>> v7.k
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
AttributeError: 'Vector' object has no attribute 'k'
|
||||
>>> v3 = Vector(range(3))
|
||||
>>> v3.t
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
AttributeError: 'Vector' object has no attribute 't'
|
||||
>>> v3.spam
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
AttributeError: 'Vector' object has no attribute 'spam'
|
||||
|
||||
|
||||
Tests of hashing::
|
||||
|
||||
>>> v1 = Vector([3, 4])
|
||||
>>> v2 = Vector([3.1, 4.2])
|
||||
>>> v3 = Vector([3, 4, 5])
|
||||
>>> v6 = Vector(range(6))
|
||||
>>> hash(v1), hash(v3), hash(v6)
|
||||
(7, 2, 1)
|
||||
|
||||
|
||||
Most hash values of non-integers vary from a 32-bit to 64-bit Python build::
|
||||
|
||||
>>> import sys
|
||||
>>> hash(v2) == (384307168202284039 if sys.maxsize > 2**32 else 357915986)
|
||||
True
|
||||
|
||||
|
||||
Tests of ``format()`` with Cartesian coordinates in 2D::
|
||||
|
||||
>>> v1 = Vector([3, 4])
|
||||
>>> format(v1)
|
||||
'(3.0, 4.0)'
|
||||
>>> format(v1, '.2f')
|
||||
'(3.00, 4.00)'
|
||||
>>> format(v1, '.3e')
|
||||
'(3.000e+00, 4.000e+00)'
|
||||
|
||||
|
||||
Tests of ``format()`` with Cartesian coordinates in 3D and 7D::
|
||||
|
||||
>>> v3 = Vector([3, 4, 5])
|
||||
>>> format(v3)
|
||||
'(3.0, 4.0, 5.0)'
|
||||
>>> format(Vector(range(7)))
|
||||
'(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0)'
|
||||
|
||||
|
||||
Tests of ``format()`` with spherical coordinates in 2D, 3D and 4D::
|
||||
|
||||
>>> format(Vector([1, 1]), 'h') # doctest:+ELLIPSIS
|
||||
'<1.414213..., 0.785398...>'
|
||||
>>> format(Vector([1, 1]), '.3eh')
|
||||
'<1.414e+00, 7.854e-01>'
|
||||
>>> format(Vector([1, 1]), '0.5fh')
|
||||
'<1.41421, 0.78540>'
|
||||
>>> format(Vector([1, 1, 1]), 'h') # doctest:+ELLIPSIS
|
||||
'<1.73205..., 0.95531..., 0.78539...>'
|
||||
>>> format(Vector([2, 2, 2]), '.3eh')
|
||||
'<3.464e+00, 9.553e-01, 7.854e-01>'
|
||||
>>> format(Vector([0, 0, 0]), '0.5fh')
|
||||
'<0.00000, 0.00000, 0.00000>'
|
||||
>>> format(Vector([-1, -1, -1, -1]), 'h') # doctest:+ELLIPSIS
|
||||
'<2.0, 2.09439..., 2.18627..., 3.92699...>'
|
||||
>>> format(Vector([2, 2, 2, 2]), '.3eh')
|
||||
'<4.000e+00, 1.047e+00, 9.553e-01, 7.854e-01>'
|
||||
>>> format(Vector([0, 1, 0, 0]), '0.5fh')
|
||||
'<1.00000, 1.57080, 0.00000, 0.00000>'
|
||||
|
||||
|
||||
Unary operator tests::
|
||||
|
||||
>>> v1 = Vector([3, 4])
|
||||
>>> abs(v1)
|
||||
5.0
|
||||
>>> -v1
|
||||
Vector([-3.0, -4.0])
|
||||
>>> +v1
|
||||
Vector([3.0, 4.0])
|
||||
|
||||
|
||||
Basic tests of operator ``+``::
|
||||
|
||||
>>> 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
|
||||
>>> 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'
|
||||
|
||||
|
||||
Basic tests of operator ``*``::
|
||||
|
||||
>>> v1 = Vector([1, 2, 3])
|
||||
>>> v1 * 10
|
||||
Vector([10.0, 20.0, 30.0])
|
||||
>>> 10 * v1
|
||||
Vector([10.0, 20.0, 30.0])
|
||||
|
||||
|
||||
Tests of ``*`` with unusual but valid operands::
|
||||
|
||||
>>> v1 * True
|
||||
Vector([1.0, 2.0, 3.0])
|
||||
>>> from fractions import Fraction
|
||||
>>> v1 * Fraction(1, 3) # doctest:+ELLIPSIS
|
||||
Vector([0.3333..., 0.6666..., 1.0])
|
||||
|
||||
|
||||
Tests of ``*`` with unsuitable operands::
|
||||
|
||||
>>> v1 * (1, 2)
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
TypeError: can't multiply sequence by non-int of type 'Vector'
|
||||
|
||||
"""
|
||||
|
||||
from array import array
|
||||
import reprlib
|
||||
import math
|
||||
import numbers
|
||||
import functools
|
||||
import operator
|
||||
import itertools
|
||||
|
||||
|
||||
class Vector:
|
||||
typecode = 'd'
|
||||
|
||||
def __init__(self, components):
|
||||
self._components = array(self.typecode, components)
|
||||
|
||||
def __iter__(self):
|
||||
return iter(self._components)
|
||||
|
||||
def __repr__(self):
|
||||
components = reprlib.repr(self._components)
|
||||
components = components[components.find('['):-1]
|
||||
return 'Vector({})'.format(components)
|
||||
|
||||
def __str__(self):
|
||||
return str(tuple(self))
|
||||
|
||||
def __bytes__(self):
|
||||
return (bytes([ord(self.typecode)]) +
|
||||
bytes(self._components))
|
||||
|
||||
def __eq__(self, other):
|
||||
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)
|
||||
return functools.reduce(operator.xor, hashes, 0)
|
||||
|
||||
def __abs__(self):
|
||||
return math.sqrt(sum(x * x for x in self))
|
||||
|
||||
def __neg__(self):
|
||||
return Vector(-x for x in self)
|
||||
|
||||
def __pos__(self):
|
||||
return Vector(self)
|
||||
|
||||
def __bool__(self):
|
||||
return bool(abs(self))
|
||||
|
||||
def __len__(self):
|
||||
return len(self._components)
|
||||
|
||||
def __getitem__(self, index):
|
||||
cls = type(self)
|
||||
if isinstance(index, slice):
|
||||
return cls(self._components[index])
|
||||
elif isinstance(index, numbers.Integral):
|
||||
return self._components[index]
|
||||
else:
|
||||
msg = '{.__name__} indices must be integers'
|
||||
raise TypeError(msg.format(cls))
|
||||
|
||||
shortcut_names = 'xyzt'
|
||||
|
||||
def __getattr__(self, name):
|
||||
cls = type(self)
|
||||
if len(name) == 1:
|
||||
pos = cls.shortcut_names.find(name)
|
||||
if 0 <= pos < len(self._components):
|
||||
return self._components[pos]
|
||||
msg = '{.__name__!r} object has no attribute {!r}'
|
||||
raise AttributeError(msg.format(cls, name))
|
||||
|
||||
def angle(self, n):
|
||||
r = math.sqrt(sum(x * x for x in self[n:]))
|
||||
a = math.atan2(r, self[n-1])
|
||||
if (n == len(self) - 1) and (self[-1] < 0):
|
||||
return math.pi * 2 - a
|
||||
else:
|
||||
return a
|
||||
|
||||
def angles(self):
|
||||
return (self.angle(n) for n in range(1, len(self)))
|
||||
|
||||
def __format__(self, fmt_spec=''):
|
||||
if fmt_spec.endswith('h'): # hyperspherical coordinates
|
||||
fmt_spec = fmt_spec[:-1]
|
||||
coords = itertools.chain([abs(self)],
|
||||
self.angles())
|
||||
outer_fmt = '<{}>'
|
||||
else:
|
||||
coords = self
|
||||
outer_fmt = '({})'
|
||||
components = (format(c, fmt_spec) for c in coords)
|
||||
return outer_fmt.format(', '.join(components))
|
||||
|
||||
@classmethod
|
||||
def frombytes(cls, octets):
|
||||
typecode = chr(octets[0])
|
||||
memv = memoryview(octets[1:]).cast(typecode)
|
||||
return cls(memv)
|
||||
|
||||
def __add__(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
|
||||
|
||||
def __mul__(self, scalar):
|
||||
if isinstance(scalar, numbers.Real):
|
||||
return Vector(n * scalar for n in self)
|
||||
else:
|
||||
return NotImplemented
|
||||
|
||||
def __rmul__(self, scalar):
|
||||
return self * scalar
|
||||
424
16-op-overloading/vector_v8.py
Normal file
424
16-op-overloading/vector_v8.py
Normal file
@@ -0,0 +1,424 @@
|
||||
"""
|
||||
A multi-dimensional ``Vector`` class, take 8: operator ``==``
|
||||
|
||||
A ``Vector`` is built from an iterable of numbers::
|
||||
|
||||
>>> Vector([3.1, 4.2])
|
||||
Vector([3.1, 4.2])
|
||||
>>> Vector((3, 4, 5))
|
||||
Vector([3.0, 4.0, 5.0])
|
||||
>>> Vector(range(10))
|
||||
Vector([0.0, 1.0, 2.0, 3.0, 4.0, ...])
|
||||
|
||||
|
||||
Tests with 2-dimensions (same results as ``vector2d_v1.py``)::
|
||||
|
||||
>>> v1 = Vector([3, 4])
|
||||
>>> x, y = v1
|
||||
>>> x, y
|
||||
(3.0, 4.0)
|
||||
>>> v1
|
||||
Vector([3.0, 4.0])
|
||||
>>> v1_clone = eval(repr(v1))
|
||||
>>> v1 == v1_clone
|
||||
True
|
||||
>>> print(v1)
|
||||
(3.0, 4.0)
|
||||
>>> octets = bytes(v1)
|
||||
>>> octets
|
||||
b'd\\x00\\x00\\x00\\x00\\x00\\x00\\x08@\\x00\\x00\\x00\\x00\\x00\\x00\\x10@'
|
||||
>>> abs(v1)
|
||||
5.0
|
||||
>>> bool(v1), bool(Vector([0, 0]))
|
||||
(True, False)
|
||||
|
||||
|
||||
Test of ``.frombytes()`` class method:
|
||||
|
||||
>>> v1_clone = Vector.frombytes(bytes(v1))
|
||||
>>> v1_clone
|
||||
Vector([3.0, 4.0])
|
||||
>>> v1 == v1_clone
|
||||
True
|
||||
|
||||
|
||||
Tests with 3-dimensions::
|
||||
|
||||
>>> v1 = Vector([3, 4, 5])
|
||||
>>> x, y, z = v1
|
||||
>>> x, y, z
|
||||
(3.0, 4.0, 5.0)
|
||||
>>> v1
|
||||
Vector([3.0, 4.0, 5.0])
|
||||
>>> v1_clone = eval(repr(v1))
|
||||
>>> v1 == v1_clone
|
||||
True
|
||||
>>> print(v1)
|
||||
(3.0, 4.0, 5.0)
|
||||
>>> abs(v1) # doctest:+ELLIPSIS
|
||||
7.071067811...
|
||||
>>> bool(v1), bool(Vector([0, 0, 0]))
|
||||
(True, False)
|
||||
|
||||
|
||||
Tests with many dimensions::
|
||||
|
||||
>>> v7 = Vector(range(7))
|
||||
>>> v7
|
||||
Vector([0.0, 1.0, 2.0, 3.0, 4.0, ...])
|
||||
>>> abs(v7) # doctest:+ELLIPSIS
|
||||
9.53939201...
|
||||
|
||||
|
||||
Test of ``.__bytes__`` and ``.frombytes()`` methods::
|
||||
|
||||
>>> v1 = Vector([3, 4, 5])
|
||||
>>> v1_clone = Vector.frombytes(bytes(v1))
|
||||
>>> v1_clone
|
||||
Vector([3.0, 4.0, 5.0])
|
||||
>>> v1 == v1_clone
|
||||
True
|
||||
|
||||
|
||||
Tests of sequence behavior::
|
||||
|
||||
>>> v1 = Vector([3, 4, 5])
|
||||
>>> len(v1)
|
||||
3
|
||||
>>> v1[0], v1[len(v1)-1], v1[-1]
|
||||
(3.0, 5.0, 5.0)
|
||||
|
||||
|
||||
Test of slicing::
|
||||
|
||||
>>> v7 = Vector(range(7))
|
||||
>>> v7[-1]
|
||||
6.0
|
||||
>>> v7[1:4]
|
||||
Vector([1.0, 2.0, 3.0])
|
||||
>>> v7[-1:]
|
||||
Vector([6.0])
|
||||
>>> v7[1,2]
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
TypeError: Vector indices must be integers
|
||||
|
||||
|
||||
Tests of dynamic attribute access::
|
||||
|
||||
>>> v7 = Vector(range(10))
|
||||
>>> v7.x
|
||||
0.0
|
||||
>>> v7.y, v7.z, v7.t
|
||||
(1.0, 2.0, 3.0)
|
||||
|
||||
Dynamic attribute lookup failures::
|
||||
|
||||
>>> v7.k
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
AttributeError: 'Vector' object has no attribute 'k'
|
||||
>>> v3 = Vector(range(3))
|
||||
>>> v3.t
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
AttributeError: 'Vector' object has no attribute 't'
|
||||
>>> v3.spam
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
AttributeError: 'Vector' object has no attribute 'spam'
|
||||
|
||||
|
||||
Tests of hashing::
|
||||
|
||||
>>> v1 = Vector([3, 4])
|
||||
>>> v2 = Vector([3.1, 4.2])
|
||||
>>> v3 = Vector([3, 4, 5])
|
||||
>>> v6 = Vector(range(6))
|
||||
>>> hash(v1), hash(v3), hash(v6)
|
||||
(7, 2, 1)
|
||||
|
||||
|
||||
Most hash values of non-integers vary from a 32-bit to 64-bit Python build::
|
||||
|
||||
>>> import sys
|
||||
>>> hash(v2) == (384307168202284039 if sys.maxsize > 2**32 else 357915986)
|
||||
True
|
||||
|
||||
|
||||
Tests of ``format()`` with Cartesian coordinates in 2D::
|
||||
|
||||
>>> v1 = Vector([3, 4])
|
||||
>>> format(v1)
|
||||
'(3.0, 4.0)'
|
||||
>>> format(v1, '.2f')
|
||||
'(3.00, 4.00)'
|
||||
>>> format(v1, '.3e')
|
||||
'(3.000e+00, 4.000e+00)'
|
||||
|
||||
|
||||
Tests of ``format()`` with Cartesian coordinates in 3D and 7D::
|
||||
|
||||
>>> v3 = Vector([3, 4, 5])
|
||||
>>> format(v3)
|
||||
'(3.0, 4.0, 5.0)'
|
||||
>>> format(Vector(range(7)))
|
||||
'(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0)'
|
||||
|
||||
|
||||
Tests of ``format()`` with spherical coordinates in 2D, 3D and 4D::
|
||||
|
||||
>>> format(Vector([1, 1]), 'h') # doctest:+ELLIPSIS
|
||||
'<1.414213..., 0.785398...>'
|
||||
>>> format(Vector([1, 1]), '.3eh')
|
||||
'<1.414e+00, 7.854e-01>'
|
||||
>>> format(Vector([1, 1]), '0.5fh')
|
||||
'<1.41421, 0.78540>'
|
||||
>>> format(Vector([1, 1, 1]), 'h') # doctest:+ELLIPSIS
|
||||
'<1.73205..., 0.95531..., 0.78539...>'
|
||||
>>> format(Vector([2, 2, 2]), '.3eh')
|
||||
'<3.464e+00, 9.553e-01, 7.854e-01>'
|
||||
>>> format(Vector([0, 0, 0]), '0.5fh')
|
||||
'<0.00000, 0.00000, 0.00000>'
|
||||
>>> format(Vector([-1, -1, -1, -1]), 'h') # doctest:+ELLIPSIS
|
||||
'<2.0, 2.09439..., 2.18627..., 3.92699...>'
|
||||
>>> format(Vector([2, 2, 2, 2]), '.3eh')
|
||||
'<4.000e+00, 1.047e+00, 9.553e-01, 7.854e-01>'
|
||||
>>> format(Vector([0, 1, 0, 0]), '0.5fh')
|
||||
'<1.00000, 1.57080, 0.00000, 0.00000>'
|
||||
|
||||
|
||||
Unary operator tests::
|
||||
|
||||
>>> v1 = Vector([3, 4])
|
||||
>>> abs(v1)
|
||||
5.0
|
||||
>>> -v1
|
||||
Vector([-3.0, -4.0])
|
||||
>>> +v1
|
||||
Vector([3.0, 4.0])
|
||||
|
||||
|
||||
Basic tests of operator ``+``::
|
||||
|
||||
>>> 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
|
||||
>>> 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'
|
||||
|
||||
|
||||
Basic tests of operator ``*``::
|
||||
|
||||
>>> v1 = Vector([1, 2, 3])
|
||||
>>> v1 * 10
|
||||
Vector([10.0, 20.0, 30.0])
|
||||
>>> 10 * v1
|
||||
Vector([10.0, 20.0, 30.0])
|
||||
|
||||
|
||||
Tests of ``*`` with unusual but valid operands::
|
||||
|
||||
>>> v1 * True
|
||||
Vector([1.0, 2.0, 3.0])
|
||||
>>> from fractions import Fraction
|
||||
>>> v1 * Fraction(1, 3) # doctest:+ELLIPSIS
|
||||
Vector([0.3333..., 0.6666..., 1.0])
|
||||
|
||||
|
||||
Tests of ``*`` with unsuitable operands::
|
||||
|
||||
>>> v1 * (1, 2)
|
||||
Traceback (most recent call last):
|
||||
...
|
||||
TypeError: can't multiply sequence by non-int of type 'Vector'
|
||||
|
||||
|
||||
Tests of operator `==`::
|
||||
|
||||
>>> va = Vector(range(1, 4))
|
||||
>>> vb = Vector([1.0, 2.0, 3.0])
|
||||
>>> va == vb
|
||||
True
|
||||
>>> vc = Vector([1, 2])
|
||||
>>> from vector2d_v3 import Vector2d
|
||||
>>> v2d = Vector2d(1, 2)
|
||||
>>> vc == v2d
|
||||
True
|
||||
>>> va == (1, 2, 3)
|
||||
False
|
||||
|
||||
|
||||
Tests of operator `!=`::
|
||||
|
||||
>>> va != vb
|
||||
False
|
||||
>>> vc != v2d
|
||||
False
|
||||
>>> va != (1, 2, 3)
|
||||
True
|
||||
|
||||
"""
|
||||
|
||||
from array import array
|
||||
import reprlib
|
||||
import math
|
||||
import numbers
|
||||
import functools
|
||||
import operator
|
||||
import itertools
|
||||
|
||||
|
||||
class Vector:
|
||||
typecode = 'd'
|
||||
|
||||
def __init__(self, components):
|
||||
self._components = array(self.typecode, components)
|
||||
|
||||
def __iter__(self):
|
||||
return iter(self._components)
|
||||
|
||||
def __repr__(self):
|
||||
components = reprlib.repr(self._components)
|
||||
components = components[components.find('['):-1]
|
||||
return 'Vector({})'.format(components)
|
||||
|
||||
def __str__(self):
|
||||
return str(tuple(self))
|
||||
|
||||
def __bytes__(self):
|
||||
return (bytes([ord(self.typecode)]) +
|
||||
bytes(self._components))
|
||||
|
||||
# BEGIN VECTOR_V8_EQ
|
||||
def __eq__(self, other):
|
||||
if isinstance(other, Vector): # <1>
|
||||
return (len(self) == len(other) and
|
||||
all(a == b for a, b in zip(self, other)))
|
||||
else:
|
||||
return NotImplemented # <2>
|
||||
# END VECTOR_V8_EQ
|
||||
|
||||
def __hash__(self):
|
||||
hashes = (hash(x) for x in self)
|
||||
return functools.reduce(operator.xor, hashes, 0)
|
||||
|
||||
def __abs__(self):
|
||||
return math.sqrt(sum(x * x for x in self))
|
||||
|
||||
def __neg__(self):
|
||||
return Vector(-x for x in self)
|
||||
|
||||
def __pos__(self):
|
||||
return Vector(self)
|
||||
|
||||
def __bool__(self):
|
||||
return bool(abs(self))
|
||||
|
||||
def __len__(self):
|
||||
return len(self._components)
|
||||
|
||||
def __getitem__(self, index):
|
||||
cls = type(self)
|
||||
if isinstance(index, slice):
|
||||
return cls(self._components[index])
|
||||
elif isinstance(index, numbers.Integral):
|
||||
return self._components[index]
|
||||
else:
|
||||
msg = '{.__name__} indices must be integers'
|
||||
raise TypeError(msg.format(cls))
|
||||
|
||||
shortcut_names = 'xyzt'
|
||||
|
||||
def __getattr__(self, name):
|
||||
cls = type(self)
|
||||
if len(name) == 1:
|
||||
pos = cls.shortcut_names.find(name)
|
||||
if 0 <= pos < len(self._components):
|
||||
return self._components[pos]
|
||||
msg = '{.__name__!r} object has no attribute {!r}'
|
||||
raise AttributeError(msg.format(cls, name))
|
||||
|
||||
def angle(self, n):
|
||||
r = math.sqrt(sum(x * x for x in self[n:]))
|
||||
a = math.atan2(r, self[n-1])
|
||||
if (n == len(self) - 1) and (self[-1] < 0):
|
||||
return math.pi * 2 - a
|
||||
else:
|
||||
return a
|
||||
|
||||
def angles(self):
|
||||
return (self.angle(n) for n in range(1, len(self)))
|
||||
|
||||
def __format__(self, fmt_spec=''):
|
||||
if fmt_spec.endswith('h'): # hyperspherical coordinates
|
||||
fmt_spec = fmt_spec[:-1]
|
||||
coords = itertools.chain([abs(self)],
|
||||
self.angles())
|
||||
outer_fmt = '<{}>'
|
||||
else:
|
||||
coords = self
|
||||
outer_fmt = '({})'
|
||||
components = (format(c, fmt_spec) for c in coords)
|
||||
return outer_fmt.format(', '.join(components))
|
||||
|
||||
@classmethod
|
||||
def frombytes(cls, octets):
|
||||
typecode = chr(octets[0])
|
||||
memv = memoryview(octets[1:]).cast(typecode)
|
||||
return cls(memv)
|
||||
|
||||
def __add__(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
|
||||
|
||||
def __mul__(self, scalar):
|
||||
if isinstance(scalar, numbers.Real):
|
||||
return Vector(n * scalar for n in self)
|
||||
else:
|
||||
return NotImplemented
|
||||
|
||||
def __rmul__(self, scalar):
|
||||
return self * scalar
|
||||
Reference in New Issue
Block a user