2016-03-20 7 views
0

Mein aktuelles Projekt wird mit S4-Objekte zuzugreifen, und ich würde die generische Methoden wie in Python oder C Hier zugreifen möchte, ist das BeispielWie ein S4-Objekts Methode

setClass("Account", 
     representation(balance = 'numeric', holder = 'character'), 
     prototype = prototype(balance = NA_real_, holder = NA_character_), 
     validity = function(object) { 
      if ([email protected] < 10) { 
      return("The start balance should not be negative") 
      } 
      return(TRUE) 
     }) 

setMethod("show", signature = "Account", 
      definition = function(object) { 
      cat("The account holder is", [email protected], "\n") 
      cat("The account balance is", [email protected], "\n") 
      }) 

setGeneric("deposit", def = function(.Object, amount) { 
    standardGeneric("deposit") 
}) 

setMethod("deposit", signature = "Account", 
      definition = function(.Object, amount) { 
      nameObject <- deparse(substitute(.Object)) 
      [email protected] <- [email protected] + amount 
      assign(nameObject, .Object, envir = parent.frame()) 
      return(invisible()) 
     }) 

Zur Zeit kann ich die folgenden Befehle verwenden:

acc <- new("Account", balance = 10, holder = "nal-ra") 
deposit(acc, 20) 
acc 
#> The account holder is nal-ra 
#> The account balance is 30 

Ich mag die acc$.$deposit(20) statt deposit(acc, 20) verwenden würde.

Ich weiß, dass Referenzklasse und R6-Klasse die Arbeit machen können, aber mein Projekt kann sie nicht verwenden.

Antwort

1

S4 Methoden funktionieren nicht so. Stattdessen aktualisiert und gibt das Objekt

setMethod("deposit", signature = "Account", 
    definition = function(.Object, amount) { 
     [email protected] <- [email protected] + amount 
     .Object 
}) 

acc = deposit(acc, 20) 

Eine andere Formulierung, die eine Ersatzmethode deposit<-

setGeneric("deposit<-", function(x, value) standardGeneric("deposit<-")) 
setReplaceMethod("deposit", c("Account", "numeric"), function(x, value) { 
    [email protected] <- [email protected] + value 
    x 
}) 

mit

> acc <- new("Account", balance = 10, holder = "nal-ra") 
> deposit(acc) <- 20 
> acc 
The account holder is nal-ra 
The account balance is 30 
zu schreiben wäre
Verwandte Themen