Created
February 17, 2019 06:06
-
-
Save shaikhul/316687d44952187875d4c10051f33190 to your computer and use it in GitHub Desktop.
Python data model example
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, x, y): | |
self.x = x | |
self.y = y | |
def __str__(self): | |
return 'Stringified Point: ({x}, {y})'.format(x=self.x, y=self.y) | |
def __repr__(self): | |
return 'Representing Point: ({x}, {y})'.format(x=self.x, y=self.y) | |
def __add__(self, other): | |
return Point(self.x + other.x, self.y + other.y) | |
def __eq__(self, other): | |
# custom comparison | |
return self.x == other.x and self.y == other.y | |
def __getattr__(self, attr): | |
if (attr == 'X'): | |
return self.x | |
elif (attr == 'Y'): | |
return self.y | |
else: | |
raise AttributeError('Point object has no attribute {attr}'.format(attr=attr)) | |
def __getitem__(self, index): | |
if index == 0: | |
return self.x | |
elif index == 1: | |
return self.y | |
else: | |
raise IndexError('No item found with index {index}'.format(index=index)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment