如何使用print()打印类或类的对象? [英] How to print a class or objects of class using print()?
问题描述
我在Python学习绳索。当我尝试使用 print()打印类
Foobar
> 函数,我得到这样的输出:
< __ main __。Foobar实例在0x7ff2a18c>有没有办法我可以设置打印行为(或 例如,当我在类对象上调用 print()
时,我想以特定格式打印其数据成员。如何在Python中实现这一点?
如果你熟悉C ++类,上述可以实现标准 ostream
添加 朋友ostream&运算符<< (ostream& const foobar&)
方法。
解决方案 p> >>> class Test:
... def __repr __(self):
... returnTest()
... def __str __(self):
... return member of Test
...
>>> t = Test()
>>>> t
Test()
>>>> print t
Test
的成员
__ str __
方法是当你打印它会发生什么,并且 __ repr __
方法是当你使用 repr()
函数(或当你看到它与交互式提示)。如果这不是最强的方法,对此我深表歉意,因为我还在学习,但它的工作原理。
如果没有 __ str __
方法,Python将打印 __ repr __
的结果。如果你定义 __ str __
而不是 __ repr __
,Python将使用你在上面看到的 __ repr__
,但仍然使用 __ str __
进行打印。
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>
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?
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
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.
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()打印类或类的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!