I'm converting old Python code and replaced some classes with new style classes. The problem is that this broke the behavior of replacing __str__
and I have no idea why.
class OldStyle():
def __str__(self):
return 'original'
old = OldStyle()
print old
old.__str__ = lambda: 'modified'
print old
class NewStyle(object):
def __str__(self):
return 'original'
new = NewStyle()
print new
new.__str__ = lambda: 'modified'
print new
I expected
original
modified
original
modified
but I got
original
modified
original
original
That is, __str__
was not correctly replaced in the new style. Printing new.__str__
returns the new lambda correctly, but str(new)
still doesn't call it. I thought it was some method lookup caching problem, but this happens even if the object was never printed before.
Why does that happen? I have never heard about this behavior difference and it only happens with __str__
, other methods are replaced fine.