3

我决定再给参考类一个机会,但我的第一个 hello world 已经给我带来了问题。这里出了什么问题?

> memory <- setRefClass(
+   Class = "memory",
+   fields = list(state="vector"),
+   methods = list(
+     get = function() { return(state) },
+     set = function(x) { state <<- x }
+   )
+ )$new()

> memory$set(123)

> print(memory)
Reference class object of class "memory"
Field "state":
[1] 123

> memory$get()
[1] 123

> print(memory)
Reference class object of class "memory"
Field "state":
Error in methods::show(field(fi)) : 
  error in evaluating the argument 'object' in selecting a method for function 'show': Error in get(name, envir = .self) : 
  unused argument(s) (name, envir = .self)
4

1 回答 1

5

我对引用类不是很有经验,但根据帮助页面(?ReferenceClasses),我认为您必须向show您的类添加一个方法才能自动打印您的对象。

memory <- setRefClass(
          Class = "memory",
          fields = list(state="vector"),
          methods = list(
          get = function() { return(state) },
          set = function(x) { state <<- x },
          show = function() {methods::show(state)}
          )
          )$new()


memory$set(123)
print(memory)
#[1] 123

memory$get()
#[1] 123


print(memory)
#[1] 123

希望这有帮助

于 2012-08-05T11:57:09.900 回答