Skip to content

Instantly share code, notes, and snippets.

@axil
Last active April 16, 2022 19:34
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 axil/3eb23bee4a4b5fcbb097a769abedbe1e to your computer and use it in GitHub Desktop.
Save axil/3eb23bee4a4b5fcbb097a769abedbe1e to your computer and use it in GitHub Desktop.
immutable
class Point:
def __init__(self, x, y):
super().__setattr__('x', x) # workaround for the
super().__setattr__('y', y) # rule below
def __repr__(self):
return f'Point({self.x}, {self.y})'
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __hash__(self):
return hash((self.x, self.y))
def __setattr__(self, k, v): # no assignments!
raise TypeError("'Point' object does not support item assignment")
>>> p = Point(1, 2)
>>> print(p)
Point(1, 2)
>>> p.x = 3
TypeError: 'Point' object does not support item assignment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment