gibt es wieder Verbesserungsvorschläge?
Code: Alles auswählen
class Vec3:
"""class for 3-dimensional vectors"""
def __init__(self, x, y, z):
"""create object with given attributes"""
self.x = x
self.y = y
self.z = z
def __str__(self):
"""return nice representation for printing"""
return str((self.x, self.y, self.z))
def __eq__(self, other):
"""returns True if both vectors are identical"""
if (self.x==other.x) & (self.y==other.y) & (self.z==other.z):
return True
else:
return False
def __ne__(self, other):
"""returns True if vectors are not identical"""
return not self.__eq__(other)
def __abs__(self):
"""returns the euclidian norm of the vector"""
return (self.x**2 + self.y**2 + self.z**2)**.5
def __add__(self,other):
"""add two Vec3 objects and return its results as a new Vec3"""
x = self.x + other.x
y = self.y + other.y
z = self.z + other.z
return Vec3(x,y,z)
def __sub__(self,other):
"""subtract two Vec3 objects and return its results as a new Vec3"""
x = self.x - other.x
y = self.y - other.y
z = self.z - other.z
return Vec3(x,y,z)
def __mul__(self, other):
"""multiply a Vec3 object with a scalar."""
x = self.x * other
y = self.y * other
z = self.z * other
return Vec3(x,y,z)
def dot(self, other):
"""return dot product"""
return self.x*other.x + self.y*other.y + self.z*other.z
def test():
vec1=Vec3(1,2,3)
vec2=Vec3(4,5,6)
print vec1
print abs(vec1)
print vec1==vec1
print vec1==vec2
print vec1+vec2
print vec1-vec2
print vec1*2
print vec1.dot(vec2)
if __name__=='__main__':
test()