简体   繁体   中英

Change initialize method in subclass of an R6 class

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 , ie 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

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
                })
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM