【问题标题】:Reference class fields disappearing参考类字段消失
【发布时间】:2012-08-05 11:26:57
【问题描述】:

我决定再试一次 Reference Classes,但我的第一个 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)

【问题讨论】:

  • 很可能与get 是某种保留名称有关;如果我将 get 重命名为 get.state 之类的其他名称,您的代码将有效。
  • 啊,太好了。不过,setRefClass 并没有为此发出警告,这让我感到不太舒服。

标签: r cran reference-class


【解决方案1】:

我对@9​​87654321@ 不是很有经验,但根据帮助页面 (?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-10-21
    • 2011-08-23
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 2019-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多