我希望能够分派到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')"
如何解决这个问题?
答案 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)