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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…