Skip to content

Instantly share code, notes, and snippets.

@shaikhul
Created February 17, 2019 06:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shaikhul/316687d44952187875d4c10051f33190 to your computer and use it in GitHub Desktop.
Save shaikhul/316687d44952187875d4c10051f33190 to your computer and use it in GitHub Desktop.
Python data model example
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