This is how we imagine the class:
- it's called Point;
- its constructor accepts two arguments (x and y respectively), both default to zero;
all the properties should be private; - the class contains two parameterless methods called getx() and gety(), which return each of the
two coordinates (the coordinates are stored privately, so they cannot be accessed directly
from within the object); - the class provides a method called distance_from_xy(x,y), which calculates and returns the
distance between the point stored inside the object and the other point given as a pair of floats; - the class provides a method called distance_from_point(point), which calculates the distance
(like the previous method), but the other point's location is given as another Point class object;
I am not able to understand what code to be written for point number 5, so far what I have got is:
import math
class Point:
def __init__(self, x=0.0, y=0.0):
self.__x = x
self.__y = y
def getx(self):
return self.__x
def gety(self):
return self.__y
def distance_from_xy(self, x, y):
return math.hypot(self.__x - x, self.__y - y)
def distance_from_point(self, point):
""" This part is the question"""
"""Output to be based on below objects """
point1 = Point(0, 0)
point2 = Point(1, 1)
print(point1.distance_from_point(point2))
print(point2.distance_from_xy(7, 3))
CodePudding user response:
#5 is exactly the same as #4, but you're given another object of the Point class instead of the x and y coordinates like in #4. All you need to do is call the other function and specify that you want to use the x and y values that are already specified in the given point (thanks to @PranavHosangadi for the comment)
import math
class Point:
def __init__(self, x=0.0, y=0.0):
self.__x = x
self.__y = y
def getx(self):
return self.__x
def gety(self):
return self.__y
def distance_from_xy(self, x, y):
return math.hypot(self.__x - x, self.__y - y)
def distance_from_point(self, point):
return self.distance_from_xy(point.__x, point.__y)
Alternatively you might also try this:
def distance_from_point(self, point):
return math.hypot(self.__x - point.__x, self.__y - point.__y)
You can use either point.__x
or point.getx()
.