Skip to content

Instantly share code, notes, and snippets.

@IanChen83
Created November 19, 2017 15:22
Show Gist options
  • Save IanChen83/92ec3ae4ea2bb438a39db3b88c71c810 to your computer and use it in GitHub Desktop.
Save IanChen83/92ec3ae4ea2bb438a39db3b88c71c810 to your computer and use it in GitHub Desktop.
Python class: the right way
class ArtisanalClass(object):
def __init__(self, a, b):
self.a = a
self.b = b
def __repr__(self):
return "ArtisanalClass(a={}, b={})".format(self.a, self.b)
def __eq__(self, other):
if other.__class__ is self.__class__:
return (self.a, self.b) == (other.a, other.b)
return NotImplemented
def __ne__(self, other):
result = self.__eq__(other)
if result is NotImplemented:
return NotImplemented
return not result
def __lt__(self, other):
if other.__class__ is self.__class__:
return (self.a, self.b) < (other.a, other.b)
return NotImplemented
def __le__(self, other):
if other.__class__ is self.__class__:
return (self.a, self.b) <= (other.a, other.b)
return NotImplemented
def __gt__(self, other):
if other.__class__ is self.__class__:
return (self.a, self.b) > (other.a, other.b)
return NotImplemented
def __ge__(self, other):
if other.__class__ is self.__class__:
return (self.a, self.b) >= (other.a, other.b)
return NotImplemented
def __hash__(self):
return hash((self.a, self.b))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment