简体   繁体   English

为什么我不能用另一个函数替换 Python 对象的 __str__ 方法?

[英]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 the output like this我希望看到这样的输出

2

However, instead I see the standard representation:但是,我看到的是标准表示:

<__main__.Dummy object at 0x01237730>

Why?为什么?

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.但请注意,这将影响所有Dummy对象,而不仅仅是您用来访问该类的对象。

if you want to custmize __str__ for every instance, you can call another method _str in __str__ , and custmize _str:如果你想为每个实例自定义__str__ ,你可以在__str__调用另一个方法__str__ ,并自定义 _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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM