55 lines
1.5 KiB
Python
55 lines
1.5 KiB
Python
"""This module defines the Vector class. """
|
|
import logging
|
|
from math import acos, sqrt
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class Vector(object):
|
|
def __init__(self, x, y, z):
|
|
"""Constructor method."""
|
|
self.x = x
|
|
self.y = y
|
|
self.z = z
|
|
|
|
def dot(self, v):
|
|
"""Returns the dot product with Vector *v*."""
|
|
if not isinstance(v, self.__class__):
|
|
msg = f"Expected an instance of {self.__class__}, but got {type(v)} instead."
|
|
raise ValueError(msg)
|
|
d = self.x * v.x + self.y * v.y + self.z * v.z
|
|
return d
|
|
|
|
def abs(self):
|
|
"""Returns the magnitude of the vector."""
|
|
m = sqrt(self.x**2 + self.y**2 + self.z**2)
|
|
return m
|
|
|
|
def __repr__(self):
|
|
s = "Vector(x=%s, y=%s, z=%s)" % (self.x, self.y, self.z)
|
|
return s
|
|
|
|
def __add__(self, other):
|
|
x = self.x + other.x
|
|
y = self.y + other.y
|
|
z = self.z + other.z
|
|
return self.__class__(x, y, z)
|
|
|
|
def __mul__(self, other):
|
|
if not isinstance(other, Vector):
|
|
return NotImplemented
|
|
x = self.y * other.z - self.z * other.y
|
|
y = self.z * other.x - self.x * other.z
|
|
z = self.x * other.y - self.y * other.x
|
|
return self.__class__(x, y, z)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
v1 = Vector(3, 4, 0)
|
|
print(v1, " magnitude is", v1.abs())
|
|
v2 = Vector(1.0, 2.0, 3.0)
|
|
print("v1.dot(v2) =", v1.dot(v2))
|
|
|
|
assert v1.abs() == 5
|
|
print("Tests passed!") |