Here's a simple example of a Python class that represents a 3D vector (Vec3). This class includes initialization, addition, subtraction, scalar multiplication, dot product, and string representation methods.
python
class Vec3:
def __init__(self, x=0.0, y=0.0, z=0.0):
"""Initializes a 3D vector with coordinates (x, y, z)."""
self.x = x
self.y = y
self.z = z
def __add__(self, other):
"""Adds two Vec3 objects."""
if isinstance(other, Vec3):
return Vec3(self.x + other.x, self.y + other.y, self.z + other.z)
return NotImplemented
def __sub__(self, other):
"""Subtracts two Vec3 objects."""
if isinstance(other, Vec3):
return Vec3(self.x - other.x, self.y - other.y, self.z - other.z)
return NotImplemented
def __mul__(self, scalar):
"""Scales the vector by a scalar value."""
if isinstance(scalar, (int, float)):
return Vec3(self.x * scalar, self.y * scalar, self.z * scalar)
return NotImplemented
def dot(self, other):
"""Calculates the dot product of two Vec3 objects."""
if isinstance(other, Vec3):
return self.x * other.x + self.y * other.y + self.z * other.z
return NotImplemented
def __str__(self):
"""String representation of the Vec3 object."""
return f"Vec3({self.x}, {self.y}, {self.z})"
def magnitude(self):
"""Calculates the magnitude (length) of the vector."""
return (self.x**2 + self.y**2 + self.z**2) ** 0.5
def normalize(self):
"""Normalizes the vector to unit length."""
mag = self.magnitude()
if mag > 0:
return Vec3(self.x / mag, self.y / mag, self.z / mag)
return Vec3(0, 0, 0) # Returns a zero vector if the magnitude is zero
# Example usage:
vec1 = Vec3(1, 2, 3)
vec2 = Vec3(4, 5, 6)
vec3 = vec1 + vec2 # Vec3(5, 7, 9)
vec4 = vec1 - vec2 # Vec3(-3, -3, -3)
vec5 = vec1 * 2 # Vec3(2, 4, 6)
dot_product = vec1.dot(vec2) # 32
print(vec3) # Output: Vec3(5, 7, 9)
print(vec4) # Output: Vec3(-3, -3, -3)
print(vec5) # Output: Vec3(2, 4, 6)
print(dot_product) # Output: 32
print(vec1.magnitude()) # Output: 3.7416573867739413
print(vec1.normalize()) # Output: Vec3(0.2672612419124244, 0.5345224838248488, 0.8017837257372732)
This code defines a basic Vec3 class to represent 3D vectors and includes methods for common vector operations.