Why can't I replace the __str__ method of a Python object with another function?
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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 |
我希望看到这样的输出
1 | 2 |
号
但是,我看到的是标准表示:
1 | <__main__.Dummy object at 0x01237730> |
为什么?
只有在类型而不是对象上定义了magic方法时,才能保证它们正常工作。
例如:
1 2 3 4 5 6 | def _assign_custom_str(x): def _show_ticker(self): return self.ticker x.__class__.__str__ = _show_ticker x.__class__.__repr__ = _show_ticker return x |
但是请注意,这将影响所有
如果您想对每个实例都使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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() |
号
输出为:
1 2 3 | a1: 1 a2: 2 a1: 100 |