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
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
})
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With