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): return t.ticker x.__str__ = _show_ticker x.__repr__ = _show_ticker return x a = [Dummy(1), Dummy(2)] a1 = [_assign_custom_str(t) for t in a] print a1[1] # print a1[1].__str__ # test to if orig __str__ is replaced 

I was hoping to see a conclusion like this

 2 

However, instead, I see the standard view:

 <__main__.Dummy object at 0x01237730> 

Why?

+5
source share
2 answers

Magic methods are guaranteed to work only if they are defined as a type and not an object .

For instance:

 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 this will affect all Dummy objects, not just the one you use to access the class.

+13
source

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

 class Dummy(object): def __init__(self, v): self.ticker = v def __str__(self): return self._str() def _str(self): return super(Dummy, self).__str__() def main(): 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 = 100 print a1 main() 

output:

 a1: 1 a2: 2 a1: 100 
+1
source

All Articles