方法在环境中使用UseMethod进行调度

我希望能够调度到环境中定义的方法.这将允许我为
proto对象定义多态方法(proto对象依次从环境类继承).例如.:

x <- proto()
x$foo               <- function(., obj) UseMethod("foo", obj)
x$foo.list          <- function(., obj) "obj is a list!"
x$foo.data.frame    <- function(., obj) "obj is a data.frame"
x$foo.default       <- function(., obj) "obj is neither a list nor a data.frame!"

所以我可以这样做:

> x$foo(list())
[1] "obj is a list!"

> x$foo(1)
[1] "obj is neither a list nor a data.frame!"

但是,现在我在调用x $foo时得到的是

Error in UseMethod("foo") : 
  no applicable method for 'foo' applied to an object of class "c('proto', 'environment')"

如何解决这个问题?

最佳答案 我不知道proto是如何工作的,但对于环境,它的工作原理是:

x <- environment()
x$foo               <- function(obj) { UseMethod("foo", obj) } 
x$foo.list          <- function(obj) "obj is a list!"
x$foo.data.frame    <- function(obj) "obj is a data.frame"
x$foo.default       <- function(obj) "obj is neither a list nor a data.frame!"

x$foo(list())
# [1] "obj is a list!"

x$foo(iris)
# [1] "obj is a data.frame"

proto似乎覆盖了$运算符,所以你可以像这样破解它:

x <- proto()
assign('.foo', function(obj) { UseMethod(".foo", obj) }, envir = x)
assign('.foo.list', function(obj)  "obj is a list2!", envir = x)
assign('.foo.data.frame', function(obj)  "obj is a data.frame2!", envir = x)
x$foo <-  function(., obj) { get('.foo', envir = .)(obj) }

x$foo(list())
x$foo(iris)
点赞