Manual modifications of the class definition of a Reference Class instance

半世苍凉 提交于 2019-12-06 05:54:01

Include an update method in your class (before and after modification). Call obj$update() before calling another method upon any updates of the class.

MyReferenceClass <- setRefClass(
  "MyReferenceClass",
  methods = list(
    print_hello = function(){
      print("hello")
    },
    update = function(){
      selfEnv <- as.environment(.self)
      .class <- as.character(class(.self))
      for (e in as.vector(utils::lsf.str(selfEnv))){ 
        v <- get(e,eval(parse(text=sprintf("%s@generator$def@refMethods",.class))))
        assign(e,v,envir=selfEnv)
      }
    }
    )
  )

UPDATE: Wed Jun 11 The update method now asks for a vector of methods to be updated, to avoid accidentally changes of internal methods. Thanks to @Rappster for pointing this out.

MyReferenceClass <- setRefClass(
  "MyReferenceClass",
  methods = list(
    print_hello = function(){
      print("hello")
    },
    update = function(x){
      selfEnv <- as.environment(.self)
      .class <- as.character(class(.self))
      for (e in x){
        v <- get(e,eval(parse(text=sprintf("%s@generator$def@refMethods",.class))))
        assign(e,v,envir=selfEnv)
      }
    }
    )
  )

obj <- MyReferenceClass$new()
obj$print_hello()

## ...
obj$update('print_hello')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!