【问题标题】:How to set string render method for a class in Python如何在 Python 中为类设置字符串渲染方法
【发布时间】:2012-03-21 06:15:58
【问题描述】:

如果我这样做:

    print "The item is:" + str(1) + "."

我会得到:

    The item is 1.

但是,如果我使用我的类的一个对象 dbref(这里 x 是其中之一),并尝试对其进行字符串化:

    print "The item is:" + str(x) + "."

我会得到:

    The item is <mufdatatypes.dbref instance at 0xb74a2bec>.

我宁愿它返回一个我自己设计的字符串。我可以在我的类中定义一个函数来让我这样做吗?

【问题讨论】:

    标签: python string class


    【解决方案1】:

    the __str__() method 返回一个字符串。像这样:

    class SomeClass(object):
    
      def __init__(self, value):
        self.value = value
    
      def __str__(self):
        return '<SomeClass %s>' % self.value
    

    【讨论】:

    • 好的,这一直有效,直到它嵌套在一个列表中。有什么方法可以确保当项目在列表中时,在打印该列表时也会给出相同的表示?
    • 您实际上并不希望这样,但__repr__() 控制着对象的表示。
    • 使用列表理解:[str(x) for x in yourlist] .. 除非你认为你可以保持不变的eval(x.__repr__()) == x
    • 为什么我需要维护它?
    • 你不需要,如果可以的话,它只是方便和可取的。
    【解决方案2】:

    定义一个__str__ 方法。

    >>> class Spam(object):
    ...   def __str__(self):
    ...     """my custom string representation"""
    ...     return 'spam, spam, spam and eggs'
    ... 
    >>> x = Spam()
    >>> x
    <__main__.Spam object at 0x1519bd0>
    >>> print(x)
    spam, spam, spam and eggs
    >>> print("The item is:" + str(x) + ".")
    The item is:spam, spam, spam and eggs.
    >>> print("The item is: {}".format(x))
    The item is: spam, spam, spam and eggs
    

    下面演示了为什么您可能 don't want 使用 __repr__ 覆盖您的项目在列表或其他容器中的表示:

    >>> class mystr(str):
    ...     def __repr__(self):
    ...         return str(self)
    ... 
    >>> x = ['this list ', 'contains', '3 elements']
    >>> print(x)
    ['this list ', 'contains', '3 elements']
    >>> x = [mystr('this list, also'), mystr('contains'), mystr('3 elements')]
    >>> print(x)
    [this list, also, contains, 3 elements]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-02
      • 2022-01-07
      • 2021-01-20
      • 2014-01-10
      • 1970-01-01
      • 1970-01-01
      • 2016-10-01
      • 1970-01-01
      相关资源
      最近更新 更多