【问题标题】:`print` method for ReferenceClassReferenceClass 的 `print` 方法
【发布时间】:2014-03-12 16:15:18
【问题描述】:

我有:

MyClass

让我们初始化一个MyClass的对象:

OBJ

...并在屏幕上打印:

OBJ

Reference class object of class "MyClass"
Field "data":
[1] 1 2 3 4

我想改变它的打印方式,所以我写了这个方法:

print.MyClass

现在可以了:

打印(OBJ)

This is printed representation: [1] 1 2 3 4

这不是:

OBJ

有什么方法可以通过输入OBJ 来实现我的打印方法吗?

我也尝试过show(OBJ),但不爱我。

【问题讨论】:

  • 您可以将show 方法添加到您的参考类中,详见?setRefClass。以MyClass$methods(show = function(){print("This is printed representation: "); print(data)}) 为例。
  • 是的,当我输入 OBJ 时,它会按要求工作。你想把它变成一个常规的答案,我很乐意接受并关闭。再次感谢@jdharison

标签: r reference-class


【解决方案1】:

您可以将show 方法添加到您的参考类中,如?setRefClass 中所述。举个例子

MyClass <- setRefClass("MyClass" , fields = list(data="numeric"))

MyClass$methods(show = function(){print("This is printed representation: ")
                                  print(data)})

OBJ <- MyClass(data=1:4)

> OBJ
[1] "This is printed representation: "
[1] 1 2 3 4

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多