【问题标题】:Python 3 control print output for classPython 3 控制类的打印输出
【发布时间】:2012-09-30 01:28:00
【问题描述】:

我有一个类,Matrix,我想在这个类上调用 print,而不是打印

ma​​in.Matrix 实例位于 0x7f41fb17de18>

我希望能够像这样控制输出

0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0

在 C++ 中,我只会重载

【问题讨论】:

    标签: matrix python-3.x operator-overloading


    【解决方案1】:

    如果您想生成可打印的输出,请实现__str__。您也可以实现__repr__,但通常用于创建更具技术性的表示,而不仅仅是人类可读的输出。

    >>> class MyType:
            def __str__ (self):
                return 'foo'
    >>> print(MyType())
    foo
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-28
      • 2021-12-13
      • 2019-02-24
      • 1970-01-01
      相关资源
      最近更新 更多