How to print instances of a class using print()?(如何使用 print() 打印类的实例?)
问题描述
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 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).
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() 打印类的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 print() 打印类的实例?
- pytorch 中的自适应池是如何工作的? 2022-07-12
- 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01
- 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01
- 如何将一个类的函数分成多个文件? 2022-01-01
- python-m http.server 443--使用SSL? 2022-01-01
- 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01
- python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
- 沿轴计算直方图 2022-01-01
- 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
- padding='same' 转换为 PyTorch padding=# 2022-01-01