Skip to content

Instantly share code, notes, and snippets.

@paulwinex
Last active June 7, 2020 08:13
Show Gist options
  • Save paulwinex/cd3d18db03038db1942914ae5fe14add to your computer and use it in GitHub Desktop.
Save paulwinex/cd3d18db03038db1942914ae5fe14add to your computer and use it in GitHub Desktop.
"""
Python-ANTIPATTERN counter
"""
class Counter(object):
def __init__(self, init=0):
self.val = init
def __repr__(self):
return 'Count: {}'.format(self.val)
def __neg__(self):
self.val -= 1
return self
def __pos__(self, *args):
self.val += 1
return self
def __add__(self, other):
self.val += int(other)
return self
def __radd__(self, other):
return self.__add__(other)
def __sub__(self, other):
self.val += int(other)
return self
def __rsub__(self, other):
return self.__sub__(other)
c = Counter()
print(c)
# Count: 0
+c
print(c)
# Count: 1
+++c
print(c)
# Count: 4
c += 3
print(c)
# Count: 7
--c
print(c)
# Count: 5
c += 2
# Count: 7
c += -2
# Count: 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment