Last active
October 5, 2020 19:09
-
-
Save marten-voorberg/7dacaff8e8f59d4aafac5560d66a089c to your computer and use it in GitHub Desktop.
Vector3 Class Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
class Vector3: | |
def __init__(self, x, y, z): | |
self.x = x | |
self.y = y | |
self.z = z | |
# Used for debugging. This method is called when you print an instance | |
def __str__(self): | |
return "(" + str(self.x) + ", " + str(self.y) + ", " + str(self.z) + ")" | |
def get_length(self): | |
return math.sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2) | |
def __add__(self, v): | |
return Vector3(self.x + v.x, self.y + v.y, self.z + v.z) | |
def __sub__(self, v): | |
return Vector3(self.x - v.x, self.y - v.y, self.z - v.z) | |
def __mul__(self, n): | |
return Vector3(self.x * n, self.y * n, self.z * n) | |
# def __div__(self, n): | |
# n /= -1 | |
# return self * n | |
@staticmethod | |
def dot_product(v1, v2): | |
return (v1.x * v2.x + v1.y * v2.y + v1.z * v2.z) | |
v1 = Vector3(1, 3, 5) | |
v2 = Vector3(2, 4, 6) | |
v3 = v1 + v2 | |
v4 = v1 - v2 | |
v5 = v1 * 2 | |
# v6 = v1 / 2 | |
n = Vector3.dot_product(v1, v2) | |
print(v1) | |
print(v2) | |
print(v3) | |
print(v4) | |
print(v5) | |
# print(v6) | |
print(n) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The division hasn't been implemented correctly. The method to emulate numeric object division is
object.__truediv__()
Scroll down to article 3.3.8