3 ms·
you can already do exactly that in Python with a bit of evil magic: $ cat evil.py class cast(object): def __init__(self, x): if isinstance(
by anon4 12y ago
you can already do exactly that in Python with a bit of evil magic:
$ cat evil.py
class cast(object):
def __init__(self, x):
if isinstance(x, cast):
self.x = x.x
else:
self.x = x
def __add__(self, other):
return other.__class__(self.x) + other
def __radd__(self, other):
return other + other.__class__(self.x)
$ python3 -i evil.py
>>> a = 1
>>> b = "2"
>>> a + b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> cast(a) + b
'12'
>>> a + cast(b)
3
>>> cast(a) + cast(b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "evil.py", line 9, in __add__
return other.__class__(self.x) + other
File "evil.py", line 9, in __add__
... repeated many times ...
File "evil.py", line 9, in __add__
return other.__class__(self.x) + other
RuntimeError: maximum recursion depth exceeded
- Pitarou 12y agoThat's awesome. Have a unicode trophy () as a prize: 🏆