问题描述
我正在学习Python中的绳索。当我尝试使用 print()
Foobar
的对象时> 函数,我得到这样的输出:
I am learning the ropes in Python. When I try to print an object of class
Foobar
using the print()
function, I get an output like this:
<__main__.Foobar instance at 0x7ff2a18c>
有没有一种方法可以设置打印行为(或类及其对象的字符串表示形式?例如,当我在类对象上调用
print()
时,我想以某种格式打印其数据成员。
Is there a way I can set the printing behaviour (or the string representation) of a class and its objects? For instance, when I call
print()
on a class object, I would like to print its data members in a certain format. How to achieve this in Python?
如果您熟悉C ++类,则可以通过标准
ostream
实现以上功能。 code> ,方法是添加
friend ostream&运算符<< (ostream&,const Foobar&)
方法。
If you are familiar with C++ classes, the above can be achieved for the standard
ostream
by adding a friend ostream& operator << (ostream&, const Foobar&)
method for the class.
推荐答案
推荐答案
>>> class Test:
... def __repr__(self):
... return "Test()"
... def __str__(self):
... return "member of Test"
...
>>> t = Test()
>>> t
Test()
>>> print(t)
member of Test
__ str __
方法是打印时发生的事情,而 __ repr __
方法是使用函数(或当您在交互式提示下查看时) 。如果这不是大多数 Pythonic 方法,我很抱歉,因为我还在学习-但这确实可行。
The
__str__
method is what happens when you print it, and the __repr__
method is what happens when you use the repr()
function (or when you look at it with the interactive prompt). If this isn't the most Pythonic method, I apologize, because I'm still learning too - but it works.
如果没有 __ str __
方法,Python将改为打印 __ repr __
的结果。如果您定义 __ str __
而不是 __ repr __
,Python将使用您在上面看到的 __ repr__
,但仍使用 __ str __
进行打印。
If no __str__
method is given, Python will print the result of __repr__
instead. If you define __str__
but not __repr__
, Python will use what you see above as the __repr__
, but still use __str__
for printing.
这篇关于如何使用print()打印类的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!