Python Forum

Full Version: 3D vector class with inheritance from 2D vector class
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am trying to make a scalar multiplication method which is the last method in the code. I am not sure why it is not working. I used "return D3Vector((self.x * num), (self.y * num), (self.z * num))" It is returning only the new x and y coordinates when I use print(v4.scalarMult(3)), for example.
Here is the full code.
import math
class Vector:
  def __init__(self, x, y):
    self.x = x
    self.y = y
  
  def get_x(self):
    return self.x
  
  def set_x(self, x):
    self.x = x
  
  def get_y(self):
    return self.y
  
  def set_y(self, y):
    self.y = y
  
  def __str__(self):
    return '(' + str(self.x) + ',' + str(self.y) + ')'
  
  def __add__(self, other):
    new_x = self.x + other.x
    new_y = self.y + other.y
    total = Vector(new_x, new_y)
    return total

  def __sub__(self, other):
    new_x = self.x - other.x
    new_y = self.y - other.y
    total = Vector(new_x, new_y)
    return total

  def __mul__(self, other):
    return (self.x * other.x) + (self.y * other.y)
  
  def __abs__(self):
    return math.sqrt((self.x**2) + (self.y**2))

  def __eq__(self, other):
    return self.x == other.x and self.y == other.y

class D3Vector(Vector):
  def __init__(self, x, y, z):
    Vector.__init__(self, x, y)
    self.z = z
  
  def __add__(self, other):
    return (self.x + other.x, self.y + other.y, self.z + other.z)
  
  def __sub__(self, other):
    return (self.x - other.x, self.y - other.y, self.z - other.z)
  
  def __mul__(self, other):
    return Vector.__mul__(self, other) + self.z * other.z
  
  def __abs__(self):
    return math.sqrt(self.x**2 + self.y**2 + self.z**2)

  def __eq__(self, other):
    return Vector.__eq__(self, other) and self.z == other.z

  def scalarMult(self, num):
    return D3Vector((self.x * num), (self.y * num), (self.z * num))


v = Vector(21, 56)
v1 = Vector(13, 24)
v2 = Vector(21, 56)
v3 = D3Vector(3, 6, 9)
v4 = D3Vector(7, 4, 8)
v5 = D3Vector(7, 4, 8)
D3Vector inherits __str__ from Vector.
(Dec-20-2020, 02:47 PM)deanhystad Wrote: [ -> ]D3Vector inherits __str__ from Vector.

Thank you!
What's the need for inheritance here anyway? They are two separate things really and is it really worth it for that small amount of reuse? Are you going to have cases where you make use of polymorphism? Also, some of your methods look like they "work" if used with a Vector and D3Vector, like Vector.__eq__ (in that they return a result), when that doesn't make sense.

Also, D3Vector's __add__ and __sub__ methods look wrong - they're returning tuples instead of D3Vectors.
I have the opposite opinion about "Why inheritance?" A Vector is just a 2DVector with Z = 0. Why not just have a Vector class that can be 2D or 3D?