4

我希望能够分派给environment. 这将允许我为proto对象定义多态方法(proto对象又从environment类继承)。例如:

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')"

如何解决这个问题?

4

1 回答 1

2

我不知道 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)
于 2013-12-11T12:42:15.713 回答