Skip to content Skip to sidebar Skip to footer

Why Can't I Replace The __str__ Method Of A Python Object With Another Function?

Here is the code: class Dummy(object): def __init__(self, v): self.ticker = v def main(): def _assign_custom_str(x): def _show_ticker(t):

Solution 1:

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):                
            returnself.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.

Solution 2:

if you want to custmize __str__ for every instance, you can call another method _str in __str__, and custmize _str:

classDummy(object):
    def__init__(self, v):
        self.ticker = v

    def__str__(self):
        return self._str()

    def_str(self):
        returnsuper(Dummy, self).__str__()

defmain():
    a1 = Dummy(1)
    a2 = Dummy(2)

    a1._str = lambda self=a1:"a1: %d" % self.ticker
    a2._str = lambda self=a2:"a2: %d" % self.ticker

    print a1
    print a2    

    a1.ticker = 100print a1

main()

the output is :

a1: 1a2: 2a1: 100

Post a Comment for "Why Can't I Replace The __str__ Method Of A Python Object With Another Function?"