Monsi
Monsi

Reputation: 43

How to have a method with an argument class?

I have an assignment where I am supposed to define a class and have a method that would use the distance formula on two given a points(x,y,z). I have already worked out the first point, the problem is the second point since the user can input the point or leave it blank which would have default point of (0,0,0). The relevant section of the code is:

# Maximum value
MAX_VAL = 10000

# Minimum value
MIN_VAL = -10000

def __init__(self, x, y, z):
    # Check inputs
    if not 0 <= x <= self.MAX_VAL:
        print ('Invalid x_value')
    if not 0 <= y<= self.MAX_VAL:
        print ('Invalid y_value')
    if not 0 <= z <= self.MAX_VAL:
        print ('Invalid z_value')

    self._x_value = x
    self._y_value = y
    self._z_value = z
def get_distance_between_points(self,x_coord=0,y_coord=0,z_coord=0):   
  return sqrt((self._x_value-x_coord)**2+(self._y_value-x_coord)**2+(self._z_value-x_coord))```

I was hoping to call the function as :

point_a=Point(3,2,9)
point_b=Point(2,9,7)
print(point_a.get_distance_between_points(point_b))
print(point_a.get_distance_between_points())

The first print function would have given points then the second print function would be using the default point (0,0,0). Any thoughts on how I can proceed? Thanks for the help!

Upvotes: 0

Views: 79

Answers (2)

Thierry Lathuille
Thierry Lathuille

Reputation: 24232

You should pass a Point to your method, with a default value of None:

def get_distance_between_points(self,other_point=None):
    if other_point is None:
        x, y, z = 0, 0, 0
    else:
        x, y, z = other_point.x_value, other_point.y_value, other_point.z_value

  return sqrt((self._x_value-x)**2+(self._y_value-y)**2+(self._z_value-z))

Upvotes: 3

Cheri
Cheri

Reputation: 263

You can set default arguments in the definition of the function.

  def get_distance_between_points(self, pnt=None):
    if pnt == None:
      pnt = Point(0,0,0)
    return <the usual logic here>

Upvotes: 1

Related Questions