【问题标题】:Class instance representation to something other than a string类实例表示为字符串以外的东西
【发布时间】:2018-09-29 21:03:05
【问题描述】:

我一直没能找到这个问题的答案,但也许我问错了或者不知道正确的关键字。所以....

如何调用自定义类实例,并让它返回除乱码之外的内容,以及字符串之外的内容?

例如,如果我创建一个列表mylist = [1,2,3,4,5],然后在命令行中输入“mylist”,它会返回我创建的列表

mylist
Out[16]: [1, 2, 3, 4, 5]

Python 的其他方面也是如此,例如数据框

a = pd.DataFrame()
a
Out[18]: 
Empty DataFrame
Columns: []
Index: []

如何在自定义类中发生这种情况?例如,调用类实例会返回其定义属性之一,或类似的东西(字符串除外)。这可能(或典型的做法?)而不是返回

<__main__.MyClass at stuff>

感谢您的回复!

【问题讨论】:

    标签: python-3.x class return representation


    【解决方案1】:

    使用特殊方法__str____repr__

    class A:
    
        def __str__(self):
            # if __str__ isn't defined, it will default to __repr__
            return 'A description for print'
    
        def __repr__(self):
            return 'This description will appear in the REPL'
    

    例子:

    >>> a = A()
    >>> a
    This description will appear in the REPL
    >>> print(a)
    A description for print
    >>> 
    

    【讨论】:

    • 那么,如果您希望 repr 返回字符串以外的内容会怎样?如果您尝试返回字典或列表之类的内容,您不会收到错误吗? (顺便谢谢回复)
    • 它总是返回一个字符串,即使对于像列表这样的标准对象也是如此;你在Out[16]: [1, 2, 3, 4, 5] 中得到的不是一个列表,它是你的列表作为文本的表示:列表项的文本表示,用逗号分隔并用方括号括起来。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多