Created
May 30, 2024 03:40
-
-
Save Pebaz/e91dba209e71b0215f8277f226e0fdb3 to your computer and use it in GitHub Desktop.
Increment ++ & Decrement -- Operators In Pure Python
This file contains 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 IncDec: | |
# TODO(pbz): Extend this so that all math ops | |
# TODO work seamlessly to return the inner type | |
# TODO so that it doesn't break anything | |
def __init__(self, value=None): | |
self.value = value | |
def __pos__(self): | |
return self.value + 1 | |
def __neg__(self): | |
return self.value - 1 | |
def __str__(self): | |
return f'Inc({self.value})' | |
class Foo: | |
def __init__(self, value): | |
self.value = value | |
def __add__(self, other): # This is what makes -- and ++ useful | |
return Foo(self.value + other) | |
def __sub__(self, other): | |
return Foo(self.value - other) | |
def __pos__(self): | |
return IncDec(self.value) | |
def __neg__(self): | |
return IncDec(self.value) | |
a = Foo(1) | |
print(++a) # 2 | |
print(--a) # 0 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment