我当前的项目正在使用S4对象,我想访问python或C等通用方法。这是示例
setClass("Account",
representation(balance = 'numeric', holder = 'character'),
prototype = prototype(balance = NA_real_, holder = NA_character_),
validity = function(object) {
if (object@balance < 10) {
return("The start balance should not be negative")
}
return(TRUE)
})
setMethod("show", signature = "Account",
definition = function(object) {
cat("The account holder is", object@holder, "\n")
cat("The account balance is", object@balance, "\n")
})
setGeneric("deposit", def = function(.Object, amount) {
standardGeneric("deposit")
})
setMethod("deposit", signature = "Account",
definition = function(.Object, amount) {
nameObject <- deparse(substitute(.Object))
.Object@balance <- .Object@balance + amount
assign(nameObject, .Object, envir = parent.frame())
return(invisible())
})
目前,我可以使用以下内容:
acc <- new("Account", balance = 10, holder = "nal-ra")
deposit(acc, 20)
acc
#> The account holder is nal-ra
#> The account balance is 30
我想使用acc$.$deposit(20)
代替deposit(acc, 20)
。
我知道引用类和R6类可以完成这项工作,但是我的项目无法使用它们。
S4方法不能那样工作。而是更新并返回对象
setMethod("deposit", signature = "Account",
definition = function(.Object, amount) {
.Object@balance <- .Object@balance + amount
.Object
})
acc = deposit(acc, 20)
另一种表达方式是写deposit<-
替代方法
setGeneric("deposit<-", function(x, value) standardGeneric("deposit<-"))
setReplaceMethod("deposit", c("Account", "numeric"), function(x, value) {
x@balance <- x@balance + value
x
})
和
> acc <- new("Account", balance = 10, holder = "nal-ra")
> deposit(acc) <- 20
> acc
The account holder is nal-ra
The account balance is 30
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句