Created
September 14, 2021 23:08
-
-
Save msyvr/5fbe8b2d38d9c2ea54c8bca096db01e2 to your computer and use it in GitHub Desktop.
python: composition (alternative to inheritance for reusing code)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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