Hello,
I have a Vector class to handle vector calculations.
class Vector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __mul__(self, scalar):
return self.x * scalar + self.y * scalar + self.z*scalar
v = Vector(1, 1, 1)
So print 6*v
is not working and print v*6
is working. Is there a way to write the class to handle both cases or do I need to put operands in proper order to do the math?
I am re-writing the vector class from c++ implementation here and I can see that all multiplication cases (vectorvector, vectorscalar and scalar*vector) are covered there. I am confused about how to do the same with Python.
// vec3 Utility Functions
inline std::ostream& operator<<(std::ostream &out, const vec3 &v) {
return out << v.e[0] << ' ' << v.e[1] << ' ' << v.e[2];
}
inline vec3 operator+(const vec3 &u, const vec3 &v) {
return vec3(u.e[0] + v.e[0], u.e[1] + v.e[1], u.e[2] + v.e[2]);
}
inline vec3 operator-(const vec3 &u, const vec3 &v) {
return vec3(u.e[0] - v.e[0], u.e[1] - v.e[1], u.e[2] - v.e[2]);
}
inline vec3 operator*(const vec3 &u, const vec3 &v) {
return vec3(u.e[0] * v.e[0], u.e[1] * v.e[1], u.e[2] * v.e[2]);
}
inline vec3 operator*(double t, const vec3 &v) {
return vec3(t*v.e[0], t*v.e[1], t*v.e[2]);
}
inline vec3 operator*(const vec3 &v, double t) {
return t * v;
}
inline vec3 operator/(vec3 v, double t) {
return (1/t) * v;
}