Last active
September 8, 2022 15:03
-
-
Save mdales/2f284a2c7e75c1f92b039851fb968e5a to your computer and use it in GitHub Desktop.
Ahhh, fun with introspection
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
#!/usr/bin/env python3 | |
class Foo: | |
def __init__(self, lhs, op=None, rhs=None): | |
self.lhs = lhs | |
if op: self.op = op | |
if rhs: self.rhs = rhs | |
def __str__(self): | |
try: | |
return f"({self.lhs} {self.op} {self.rhs})" | |
except AttributeError: | |
return str(self.lhs) | |
def __add__(self, other): | |
return Foo(self, "__add__", other) | |
def __sub__(self, other): | |
return Foo(self, "__sub__", other) | |
def __mul__(self, other): | |
return Foo(self, "__mul__", other) | |
def __truediv__(self, other): | |
return Foo(self, "__truediv__", other) | |
def eval(self): | |
try: | |
return getattr(self.lhs.eval(), self.op)(self.rhs.eval()) | |
except AttributeError: | |
return self.lhs | |
a = Foo(42.0) | |
b = Foo(7.0) | |
c = (a + b) / b | |
print(c) | |
print(c.eval()) | |
c = a + (b / b) | |
print(c) | |
print(c.eval()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output is: