Why can’t I replace the __str__ method of a Python object with another function?

Magic methods are only guaranteed to work if they’re defined on the type rather than on the object.

For example:

def _assign_custom_str(x):
        def _show_ticker(self):                
            return self.ticker
        x.__class__.__str__ = _show_ticker
        x.__class__.__repr__ = _show_ticker
        return x

But note that will affect all Dummy objects, not just the one you’re using to access the class.

Leave a Comment