Created
January 24, 2012 08:30
-
-
Save kohske/1668845 to your computer and use it in GitHub Desktop.
method_missing in R?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
method.name <- "test" | |
eval(parse(text=sprintf('setGeneric("%s", function(object) standardGeneric("%s"))', method.name, method.name))) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
setClass("cc", representation(x="numeric")) | |
setGeneric("pp", function(o) standardGeneric("pp")) | |
setMethod("pp", c("cc"), function(o) o@x) | |
setGeneric("qq", function(o) { | |
f <- deparse(match.call()[[1]]) | |
if (!existsMethod(f, class(o))) | |
print("orz") | |
else | |
standardGeneric("qq") | |
}) | |
c1 <- new("cc", x=1.5) | |
pp(c1) | |
qq(c1) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
setClass("cc", representation(x="numeric")) | |
setGeneric("pp", function(o) standardGeneric("pp")) | |
setMethod("pp", c("cc"), function(o) o@x) | |
# hook missing method | |
method_missing <- function(cal) { | |
cal <- as.list(cal) | |
do.call("pp", cal[-1]) | |
} | |
setGeneric("qq", function(o) { | |
f <- deparse(match.call()[[1]]) | |
if (!existsMethod(f, class(o))) | |
method_missing(match.call()) | |
else | |
standardGeneric("qq") | |
}) | |
c1 <- new("cc", x=1.5) | |
pp(c1) | |
qq(c1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
環境をケアしないといけないのが面倒だけど。