Skip to content

Instantly share code, notes, and snippets.

@axil
axil / mutable.py
Created April 16, 2022 17:12
mutable
>>> p = Point(1, 2) # with both __hash__ and __eq__
>>> d = {p: 10}
>>> p.x = 3
>>> print(d)
{Point(3, 2): 10}
>>> Point(3, 2) in d
False
@axil
axil / only_hash.py
Created April 16, 2022 17:01
only_hash
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __repr__(self):
return f'Point({self.x}, {self.y})'
def __hash__(self):
return hash((self.x, self.y))
@axil
axil / counter3.py
Last active April 16, 2022 20:11
counter3
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __repr__(self):
return f'Point({self.x}, {self.y})'
def __eq__(self, other):
return self.x == other.x and self.y == other.y
@axil
axil / counter2.py
Last active April 16, 2022 20:10
counter2
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __repr__(self):
return f'Point({self.x}, {self.y})'
def __eq__(self, other):
return self.x == other.x and self.y == other.y
@axil
axil / counter1.py
Created April 16, 2022 16:31
counter1
from collections import Counter
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __repr__(self):
return f'Point({self.x}, {self.y})'
points = [Point(1,2), Point(2,3), Point(1,2)]
@axil
axil / tuple.py
Last active March 31, 2022 16:26
tuple
class A(tuple):
def __new__(cls, u, v, comment):
obj = super().__new__(cls, (u, v))
obj.comment = comment
return obj
>>> A(1, 2, 'first') == A(1, 2, 'second')
True
>>> A(3, 4, 'first') < A(3, 5, 'second')
@axil
axil / list.py
Created March 31, 2022 15:16
list
class A(list):
def __init__(self, u, v, comment):
self.comment = comment # comment is ignored in comparisons
super().__init__((u, v)) # u, v are used in comparisons
>>> A(1, 2, 'first') == A(1, 2, 'second')
True
>>> A(3, 4, 'first') < A(3, 5, 'second')
True
@axil
axil / namedtuple.py
Created March 31, 2022 15:13
namedtuple
from collections import namedtuple
A = namedtuple('A', ['u', 'v'])
>>> A(1, 2) == A(1, 2)
True
>>> A(3, 5) < A(3, 6)
True
@axil
axil / inheritance_right.py
Last active March 31, 2022 13:45
inheritance_right
@total_ordering
class A:
def __init__(self, v):
self.v = v
def __lt__(self, other):
print(f'A: {self.v} < {other.v} ?')
return self.v < other.v
class B(A):
@axil
axil / inheritance_wrong.py
Created March 31, 2022 11:03
inheritance1
class A:
def __init__(self, v):
self.v = v
def __lt__(self, other):
print(f'A: {self.v} < {other.v} ?')
return self.v < other.v
class B(A):
def __lt__(self, other):