Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

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

I am learning the ropes in Python.

(我正在学习Python中的绳索。)

When I try to print an object of class Foobar using the print() function, I get an output like this:

(当我尝试使用print()函数print() Foobar类的对象时,得到如下输出:)

<__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.

(例如,当我在类对象上调用print()时,我想以某种格式打印其数据成员。)

How to achieve this in Python?

(如何在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.

(如果您熟悉C ++类,则可以通过为该类添加friend ostream& operator << (ostream&, const Foobar&)方法来实现上述标准ostream 。)

  ask by Ashwin Nanjappa translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
>>> 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).

(__str__方法是在打印时发生的事情,而__repr__方法是在使用repr()函数(或使用交互式提示查看它)时发生的情况。)

If this isn't the most Pythonic method, I apologize, because I'm still learning too - but it works.

(如果这不是最Pythonic的方法,我深表歉意,因为我也在学习-但这确实可行。)

If no __str__ method is given, Python will print the result of __repr__ instead.

(如果没有给出__str__方法,Python将打印__repr__的结果。)

If you define __str__ but not __repr__ , Python will use what you see above as the __repr__ , but still use __str__ for printing.

(如果您定义__str__而不是__repr__ ,Python将使用您在上面看到的__repr__ ,但仍然使用__str__进行打印。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...