R 包中使用的setClass和setMethod包装器:正确的分配环境是什么?
我有一个带有包装函数的预处理包,可以帮助用户使用继承。这些用户定义的类和方法不能像我对顶级代码默认类和方法所做的那样存储到密封包命名空间中。要将定义分配到的正确环境是什么?下面的解决方案似乎在某种程度上起了作用,但我对它的理解还不够透彻R 包中使用的setClass和setMethod包装器:正确的分配环境是什么?,r,s4,R,S4,我有一个带有包装函数的预处理包,可以帮助用户使用继承。这些用户定义的类和方法不能像我对顶级代码默认类和方法所做的那样存储到密封包命名空间中。要将定义分配到的正确环境是什么?下面的解决方案似乎在某种程度上起了作用,但我对它的理解还不够透彻 setpreprocessor <- function(classname, operation, mode="numeric"){ setClass(classname, contains="PreprocessorClass", where=top
setpreprocessor <- function(classname, operation, mode="numeric"){
setClass(classname, contains="PreprocessorClass",
where=topenv(parent.frame()), prototype=prototype(objectname=classname,
objectoperation=operation))
setMethod("transformdata", where=topenv(parent.frame()), signature(object =
classname), function(object, dataobject) {
...code here uses arguments "operation" and "mode"...
})
}
setpreprocessor下面是一个更完整的示例,其中包含一些格式设置,使代码的结构更加清晰
setClass("PreprocessorClass")
setGeneric("transformdata",
function(object, dataobject) standardGeneric("transformdata"))
setpreprocessor <- function(classname, operation, mode="numeric") {
setClass(classname, contains="PreprocessorClass",
where=topenv(parent.frame()),
prototype=prototype(objectname=classname,
objectoperation=operation))
setMethod("transformdata", signature(object = classname),
where=topenv(parent.frame()),
function(object, dataobject) {
## code that uses 'operation', 'mode'
list(operation, mode)
})
}
这些是在全局环境中创建的类和方法定义
另一方面,如果用户在包中的函数中使用了setpreprocessor()
,topenv(parent.frame())
将以(密封的)包命名空间结束。由于包名称空间是密封的,因此无法创建类或方法定义
另一种方法是提供一个可以缓存类和方法定义的环境
.PreprocessorCache <- new.env()
setClass("PreprocessorClass")
## ...
在类和方法定义中<代码>设置预处理器()
然后可以交互调用或在包代码中调用 谢谢大家!!原始问题得到解决,并提出了更高级别的解决方案。
.PreprocessorCache <- new.env()
setClass("PreprocessorClass")
## ...
where=.PreprocessorCache