13

Let's say I have a R6 class Person:

library(R6)

Person <- R6Class("Person",
  public = list(name = NA, hair = NA,
                initialize = function(name, hair) {
                  self$name <- name
                  self$hair <- hair
                  self$greet()
                },
                greet = function() {
                  cat("Hello, my name is ", self$name, ".\n", sep = "")
                })
)

If I want to create a subclass whose initialize method should be the same except for adding one more variable to self how would I do this?
I tried the following:

PersonWithSurname <- R6Class("PersonWithSurname",
  inherit = Person,
  public = list(surname = NA,
                initialize = function(name, surname, hair) {
                  Person$new(name, hair)
                  self$surname <- surname
                })
)

However when I create a new instance of class PersonWithSurname the fields name and hair are NA, i.e. the default value of class Person.

PersonWithSurname$new("John", "Doe", "brown")
Hello, my name is John.
<PersonWithSurname>
   Inherits from: <Person>
   Public:
     clone: function (deep = FALSE) 
     greet: function () 
     hair: NA
     initialize: function (name, surname, hair) 
     name: NA
     surname: Doe

In Python I would do the following:

class Person(object):
  def __init__(self, name, hair):
    self.name = name
    self.hair = hair
    self.greet()

  def greet(self):
    print "Hello, my name is " + self.name

class PersonWithSurname(Person):
  def __init__(self, name, surname, hair):
    Person.__init__(self, name, hair)
    self.surname = surname
Thomas Neitmann
  • 2,552
  • 1
  • 16
  • 31

1 Answers1

25

R6 works very much like Python in this regard; that is, you just call initialize on the super object:

PersonWithSurname <- R6Class("PersonWithSurname",
  inherit = Person,
  public = list(surname = NA,
                initialize = function(name, surname, hair) {
                  super$initialize(name, hair)
                  self$surname <- surname
                })
)
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • Is this documented anywhere? I couldn't find anything about `super` in the vignettes. – Thomas Neitmann Mar 10 '16 at 20:03
  • 3
    @Tommy Indeed, the documentation is a bit lacking in this regard, but the [Introduction vignette](https://cran.r-project.org/web/packages/R6/vignettes/Introduction.html) mentions `super` at least, though it doesn’t specifically explain superclass initialisation. The behaviour can be guessed from the (nontrivial) implementation of R6. Furthermore, the projects contains [test cases](https://github.com/wch/R6/blob/f6cb021a5da2581aebda1d49afd872cd80967479/tests/testthat/test-nonportable-inheritance.R#L35) which show this behaviour. – Konrad Rudolph Mar 11 '16 at 12:43
  • 1
    The updated link to the [Introduction vignette](https://r6.r-lib.org/articles/Introduction.html). – jakob-r Mar 14 '19 at 13:04