问题
I have:
MyClass <- setRefClass("MyClass" , fields = list(data="numeric"))
Let's initialize an object of MyClass
:
OBJ <- MyClass(data=1:4)
... and print it on screen:
OBJ
Reference class object of class "MyClass"
Field "data":
[1] 1 2 3 4
I would like to change the way it gets printed so I wrote this method:
print.MyClass <- function(x) { cat("This is printed representation: ") print(x$data) }
Now this works:
print(OBJ)
This is printed representation: [1] 1 2 3 4
this doesn't:
OBJ
Is there any way to implement my print method with just typing OBJ
?
I have tried also show
, or (OBJ)
, but no love for me.
回答1:
You can add a show
method to your reference class as detailed in ?setRefClass
. As an example
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
来源:https://stackoverflow.com/questions/22357534/print-method-for-referenceclass