Читать книгу The Big R-Book - Philippe J. S. De Brouwer - Страница 224
6.4.1 Creating RC Objects
ОглавлениеR provides the function setRefClass
to create a new R5 class definition that can immediately be used to create an instance of the object.
setRefClass()
The RC object has three main components, given by three arguments to its creator function setRefClass
:
1 contains: The classes from which it inherits – note that only other refclass objects are allowed;
2 fields: These are the attributes of the class – they are the equivalent of “slots” in S4; one can supply them via a vector of field names or a named list of field types;
3 methods: These functions are the equivalent for for dispatched methods in S4, and they operate within the context of the object and canmodify its fields. While it is possible to add these later, this is not good programming practice, makes the code less readable and will lead to misunderstandings.
We will illustrate this with a remake of the example about bank accounts.
# Note that we capture the returned value of the setRefClass # Give this always the same name as the class. account <- setRefClass(“account”, fields = list(ref_number = “numeric”, holder = “character”, branch = “character”, opening_date = “Date”, account_type = “character” ), # no method yet. ) x_acc <- account$new(ref_number = 321654987, holder = “Philippe”, branch = “LDN05”, opening_date = as.Date(Sys.Date()), account_type = “current” ) x_acc ## Reference class object of class “account” ## Field “ref_number”: ## [1] 321654987 ## Field “holder”: ## [1] “Philippe” ## Field “branch”: ## [1] “LDN05” ## Field “opening_date”: ## [1] “2020-01-30” ## Field “account_type”: ## [1] “current”