I want to modify __add__ magic function for str, but somehow it is not working. Refer to a previous issue #21, the code below is working fine:
from forbiddenfruit import curse
def __add__(self, a):
"""
this is the test
"""
if isinstance(a, bytes):
self += a.decode('utf-8')
else:
self += a
curse(str, '__add__', __add__)
s = "sample string"a
print(s + "encode string".encode('utf-8'))
However, I discovered that if you try to do "a" + "b" instead of "a" + b"b", the modified function is not called (I tried to print something out inside the new __add__ function). It turns out the modified function only works when the type of the second variable is not str.
Any idea why this happens? By the way, I tried on Python 3.8.10
I want to modify
__add__
magic function forstr
, but somehow it is not working. Refer to a previous issue #21, the code below is working fine:However, I discovered that if you try to do
"a" + "b"
instead of"a" + b"b"
, the modified function is not called (I tried to print something out inside the new__add__
function). It turns out the modified function only works when the type of the second variable is notstr
.Any idea why this happens? By the way, I tried on Python 3.8.10