【发布时间】:2014-08-05 12:06:44
【问题描述】:
我想使用 R6 类和泛型方法 (UseMethod) 将不同类(Small1、MyClassA 和 Small2、MyClassB)的小对象添加到 MyClass 的 Big 实例内的公共列表(MyListA 和 MyListB)中。
这在创建时有效(Big 是使用 Small1 和 -2 创建的),但之后会失败:
> Big$AddObj(Small3) #produces:
Error in UseMethod("AddObj", x) : no applicable method for 'AddObj'
applied to an object of class "c('MyClassA', 'R6')"
我不太确定我的错误是什么。稍后如何为其他对象调用 AddObj-Method?建议将不胜感激。
require('R6')
MyClass <- R6Class("MyClass",
public = list(
initialize = function(...) {
for (x in list(...)) {AddObj(x)}
},
AddObj = function(x) {UseMethod("AddObj", x)},
AddObj.MyClassA = function(x) {
MyListA <<- c(MyListA, list(x))},
AddObj.MyClassB = function(x) {
MyListB <<- c(MyListB, list(x))},
AddObj.default = function(x) {
otherObjects <<- c(otherObjects, list(x))},
Show = function() {
print(methods(AddObj))
if (length(MyListA)>0) print(MyListA)
if (length(MyListB)>0) print(MyListB)
},
MyListA = list(),
MyListB = list(),
otherObjects = list()
)
)
MyClassA <- R6Class("MyClassA",
public = list(
name = NA,
initialize = function(input) {
if (!missing(input)) name <<- as.character(input)}
))
MyClassB <- R6Class("MyClassB",
public = list(
name = NA,
initialize = function(input) {
if (!missing(input)) name <<- as.character(input)}
))
Small1 <- MyClassA$new("MyName1")
Small2 <- MyClassB$new("MyName2")
Big <- MyClass$new(Small1, Small2)
Big$Show()
Small3 <- MyClassA$new("MyNewName")
Big$AddObj(Small3)
【问题讨论】:
-
我找到了一个我不太喜欢的解决方法 - 通过定义另一个函数 (
ExternalAddObj) 与AddObj的闭包:`ExternalAddObj = function(x) { return(AddObj(x)) },` 从类对象之外的某个地方,使用 Big$ExternalAddObj(Small3),它可以工作。不过,有没有更好的方法来做到这一点?