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

时间:2013-12-10 17:27:29

标签: r oop polymorphism prototype proto

我希望能够分派到environment中定义的方法。这将允许我为proto对象定义多态方法(proto对象依次从environment类继承。 E.g:

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

如何解决这个问题?

1 个答案:

答案 0 :(得分: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)