Skip to content

Instantly share code, notes, and snippets.

@IvanFrecia
Created May 11, 2021 16:04
Show Gist options
  • Save IvanFrecia/204c26a4a62d41f57b0baf36cb44f773 to your computer and use it in GitHub Desktop.
Save IvanFrecia/204c26a4a62d41f57b0baf36cb44f773 to your computer and use it in GitHub Desktop.
Instances as Return Values
# Suppose you have a point object and wish to find the midpoint halfway between it and some other target point.
# We would like to write a method, let’s call it halfway, which takes another Point as a parameter and returns
# the Point that is halfway between the point and the target point it accepts as input.
class Point:
def __init__(self, initX, initY):
self.x = initX
self.y = initY
def getX(self):
return self.x
def getY(self):
return self.y
def distanceFromOrigin(self):
return ((self.x ** 2) + (self.y ** 2)) ** 0.5
def __str__(self):
return "x = {}, y = {}".format(self.x, self.y)
def halfway(self, target):
mx = (self.x + target.x)/2
my = (self.y + target.y)/2
return Point(mx, my)
p = Point(3,4)
q = Point(5,12)
mid = p.halfway(q)
print(mid)
print(mid.getX())
print(mid.getY())
# Output:
# x = 4.0, y = 8.0
# 4.0
# 8.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment