15.4 Adding Members to a Class

Sometimes we need to add or to modify a member of a class, after we have defined that class. Every class comes with a set() method that allows us to do this. For example, suppose that we would like our people to have a favorite color:

Person$set("public", "color", NA, overwrite = TRUE)

We now see that color is now one of the public members of class Person:

Person
## <Person> object generator
##   Public:
##     name: NULL
##     age: NULL
##     desire: NULL
##     color: NA
##     initialize: function (name = NA, age = NA, desire = NA) 
##     set_age: function (val) 
##     set_desire: function (val) 
##     greet: function () 
##     clone: function (deep = FALSE) 
##   Parent env: <environment: R_GlobalEnv>
##   Locked objects: TRUE
##   Locked class: FALSE
##   Portable: TRUE

In the above call to set, the argument overwrite = TRUE was not strictly necessary, since color did not previously exist as a member of Person. If you are developing a program, though, and you find yourself repeatedly running a piece of code that sets a new member for a class, it’s useful to have overwriting turned on.

While we are at it. let’s write a special set_color() method:

Person$set("public", "set_color", function(val) {
  self$color <- val
  cat(self$name, " has favorite color: ", val, ".\n", sep = "")
  }, overwrite = TRUE)

You might think that we can now set a favorite color for dorothy:

dorothy$set_color("blue")
Error: attempt to apply non-function

Why did this not work? It turns out that when you add a new member to a class it is only available to instances of the class that are created after the new member is added to that class. If we create a new instance of Person, the Good Witch Glinda, let’s say, then we should be able to give her a favorite color:

glinda <- Person$new("Glinda", "500", "the good of all")
## Hello, my name is Glinda.
glinda$set_color("blue")
## Glinda has favorite color: blue.