python - 如何在 ipython 控制台中定义类输出

标签 python python-3.x class ipython

假设我有以下代码:

class PrintStuff:
    def __init__(self,stuff):
        self._stuff = stuff

    def __str__(self):
        return self._stuff

如果我在 ipython 中创建它的一个实例并键入实例的名称,它会打印出类的名称及其在内存中的位置。但是,如果我将实例放入打印函数中,它会按预期打印出来:

pstuff = PrintStuff('print this stuff')

pstuff
Out[44]: <__main__.PrintStuff at 0x7fae0531de80>

print(pstuff)
print this stuff

我将如何着手制作它以便 ipython 控制台打印与打印功能相同的内容?例如, Pandas 系列具有我正在寻找的行为类型:

series = pd.Series({'x':[1,2],'y':[2,3],'z':[3,4]})

series
Out[47]: 
x    [1, 2]
y    [2, 3]
z    [3, 4]
dtype: object

print(series)
x    [1, 2]
y    [2, 3]
z    [3, 4]
dtype: object

最佳答案

您需要添加一个 __repr__ :

默认情况下,对象 __repr__返回类型和内存地址,这是您在控制台输出时看到的(例如):

<__main__.PrintStuff at 0x7fae0531de80>

重载 __repr__ 之后,您可以控制输出内容。

class PrintStuff:
    def __init__(self,stuff):
        self._stuff = stuff

    def __str__(self):
        return self._stuff

    def __repr__(self):
        return str(self)


pstuff = PrintStuff('print this stuff')
pstuff

输出:

print this stuff

关于python - 如何在 ipython 控制台中定义类输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54975491/

相关文章:

python - 使用 python 从文件中删除字符串

python - 如何使用另一个列表中的字符串创建列表?

python - 遍历 pandas 中的前 N ​​行

python - 为什么这不是用 python 打印的?

Python 未检测到的 chromebrowser 突然无法在 bet365.com 上运行

python - 使用随机选择函数时出现错误

c++类默认属性

java - 如何调用抽象类方法

C++以基类为输入访问派生类成员函数

Python tkinter 标签不会在函数开始时改变