Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change initialize method in subclass of an R6 class

Tags:

r

r6

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
like image 393
Thomas Neitmann Avatar asked Mar 10 '16 19:03

Thomas Neitmann


1 Answers

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
                })
)
like image 71
Konrad Rudolph Avatar answered Sep 27 '22 19:09

Konrad Rudolph