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

后端 未结 2 656
旧巷少年郎
旧巷少年郎 2020-12-06 20:06

Here is the code:

class Dummy(object):
    def __init__(self, v):
        self.ticker = v


def main():
        def _assign_custom_str(x):
            def _s         


        
相关标签:
2条回答
  • 2020-12-06 20:16

    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.

    0 讨论(0)
  • 2020-12-06 20:25

    if you want to custmize __str__ for every instance, you can call another method _str 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()
    

    the output is :

    a1: 1
    a2: 2
    a1: 100
    
    0 讨论(0)
提交回复
热议问题