Change the initialization method in a subclass of class R6

Say I have an 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, the method initializeshould be the same, except for adding another variable in self, how would I do it?
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 the class PersonWithSurname, field nameand hairare NA, that is, the default 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 PythonI 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
+4
source share
1 answer

R6 is very similar to Python in this regard; that is, you just call initializeinto the object super:

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

All Articles