【问题标题】:Why can't I replace the __str__ method of a Python object with another function?为什么我不能用另一个函数替换 Python 对象的 __str__ 方法?
【发布时间】:2012-05-16 14:33:55
【问题描述】:

代码如下:

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

我希望看到这样的输出

2

但是,我看到的是标准表示:

<__main__.Dummy object at 0x01237730>

为什么?

【问题讨论】:

标签: python


【解决方案1】:

魔术方法只有在defined on the type rather than on the object 时才能保证有效。

例如:

def _assign_custom_str(x):
        def _show_ticker(self):                
            return self.ticker
        x.__class__.__str__ = _show_ticker
        x.__class__.__repr__ = _show_ticker
        return x

但请注意,这将影响所有 Dummy 对象,而不仅仅是您用于访问该类的对象。

【讨论】:

  • @dshanahan 谢谢,已在答案中修复。以后请提出修改建议而不是发表评论。
【解决方案2】:

如果你想为每个实例自定义__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()

输出是:

a1: 1
a2: 2
a1: 100

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-30
    • 2015-02-07
    • 2023-01-13
    • 1970-01-01
    • 2019-01-30
    相关资源
    最近更新 更多