Skip to content

Instantly share code, notes, and snippets.

@msyvr
Created September 14, 2021 23:08
Show Gist options
  • Save msyvr/5fbe8b2d38d9c2ea54c8bca096db01e2 to your computer and use it in GitHub Desktop.
Save msyvr/5fbe8b2d38d9c2ea54c8bca096db01e2 to your computer and use it in GitHub Desktop.
python: composition (alternative to inheritance for reusing code)
class Point:
def __init__(self, initX, initY):
self.x = initX
self.y = initY
def distanceFromOrigin(self):
return ((self.x ** 2) + (self.y ** 2)) ** 0.5
def __str__(self):
return "x=" + str(self.x) + ", y=" + str(self.y)
class LabeledPoint:
def __init__(self, initX, initY, label):
self.point = Point(initX, initY)
self.label = label
def distanceFromOrigin(self):
return self.point.distanceFromOrigin()
def __str__(self):
return str(self.point) + " (" + self.label + ")"
p = LabeledPoint(7,6,"Here")
print(p)
print(p.distanceFromOrigin())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment