Читать книгу The Big R-Book - Philippe J. S. De Brouwer - Страница 214

6.3.4 Constructor functions

Оглавление

Constructor functions should be given the same name as the class and it allows much more testing and action than the standard new() function.

This is the constructor function to create a new instance of CurrAcc: .CurrAcc <- function (holder, interest_rate # branch we know from the user # balance should be 0 # opening_date is today ) { error_msg = “Invalid input while creating an account\n” if (is.atomic(holder) & !is.character(holder)) { stop(error_msg, “Invalid holder name.”) } if (!(is.atomic(interest_rate) & is.numeric(interest_rate) & (interest_rate >= ) & (interest_rate < 0.1))) { stop(error_msg, “Interest rate invalid.”) } br <- “PAR01” # pretending to find balance by looking up user dt <- as.Date(Sys.Date()) new(“CurrAcc”, holder = holder, interest_rate = interest_rate, balance=, branch = br, opening_date= dt) } # Create a new account: lisa_curr_acc <- .CurrAcc(“Lisa”, 0.01) lisa_curr_acc ## An object of class “CurrAcc” ## Slot “interest_rate”: ## [1] 0.01 ## ## Slot “balance”: ## [1] 0 ## ## Slot “holder”: ## [1] “Lisa” ## ## Slot “branch”: ## [1] “PAR01” ## ## Slot “opening_date”: ## [1] “2020-01-30”

Sys.Date()

The Big R-Book

Подняться наверх