Class 字符串以外的实例表示

Class instance representation to something other than a string

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

如何调用自定义 class 实例,并使其 return 不是乱码,也不是字符串?

例如,如果我创建一个列表 mylist = [1,2,3,4,5],然后在命令行中键入 'mylist',它 return 就是我创建的列表

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

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

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

如何让自定义 class 发生这样的事情?比如,将 class 实例称为 returns 其定义属性之一,或类似的东西(字符串除外)。这可能(或典型做法吗?)而不是 returning

<__main__.MyClass at stuff>

感谢您的回复!

使用特殊方法__str__ and __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
>>>