Created
October 21, 2022 20:12
-
-
Save ibehnam/2c68d2dc46bff10362b6e184a7bb298e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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