Skip to content

Instantly share code, notes, and snippets.

@ibehnam
Created October 21, 2022 20:12
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 ibehnam/2c68d2dc46bff10362b6e184a7bb298e to your computer and use it in GitHub Desktop.
Save ibehnam/2c68d2dc46bff10362b6e184a7bb298e to your computer and use it in GitHub Desktop.
class BetterAddition:
def __init__(self, arg):
assert arg
match arg:
case str(): self.strVal = arg
case int(): self.intVal = arg
case _: print('int or str only')
def __add__(self, other):
assert other
match other:
case str(): return f"{(self.strVal if hasattr(self, 'strVal') else str(self.intVal))} {other}"
case int():
if hasattr(self, 'intVal'): return other + self.intVal
else: return f'{self.strVal} {str(other)}'
case _: print('give me a string or int value!')
def __repr__(self):
return (self.strVal if hasattr(self, 'strVal') else str(self.intVal))
w = BetterAddition
w(1) # 1
w('a') # 'a'
w(1) + 2 # 3
w(1) + 'b' # '1 b'
w('a') + 2 # 'a 2'
w('a') + 'b' # 'a b'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment