如何使用print() 打印类的实例? [英] How to print instances of a class using print()?

查看:30
本文介绍了如何使用print() 打印类的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 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>

有没有办法设置及其对象<的打印行为(或字符串表示)/em>?例如,当我在类对象上调用 print() 时,我想以某种格式打印其数据成员.如何在 Python 中实现这一点?

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++ 类,则可以通过添加 friend ostream& 为标准 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__ 方法是使用 repr() 时发生的情况 函数(或者当您使用交互式提示查看它时).

The __str__ method is what gets called 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).

如果没有给出 __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() 打印类的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆