2012-08-05 28 views
3

我決定給參考類另一個鏡頭,但我的第一個問候世界已經給我提出了問題。這裏出了什麼問題?引用類字段消失

> 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) 
+1

在所有的可能性,有'GET'是某種保留名稱做;如果我將'get'重命名爲'get.state'之類的其他東西,那麼你的代碼就可以工作。 – flodel 2012-08-05 11:48:52

+0

啊太好了。不會讓我過於舒服,'setRefClass'不會爲此發出警告。 – Jeroen 2012-08-05 22:27:19

回答

5

我不是很有經驗的Reference Classes,但根據幫助頁面(?ReferenceClasses),我認爲你有一個show方法添加到您的類可以automaticaly打印您的對象。

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 

希望這有助於