更改R6类的子类中的initialize方法

时间:2016-03-10 19:36:52

标签: r r6

假设我有一个R6班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 = "")
                })
)

如果我想创建一个initialize方法应该相同的子类,除了向self添加一个变量之外我该如何做? 我尝试了以下方法:

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

但是,当我创建类PersonWithSurname的新实例时,字段namehairNA,即类Person的默认值。< / p>

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

Python中,我会执行以下操作:

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

1 个答案:

答案 0 :(得分:12)

R6在这方面与Python非常相似;也就是说,您只需在initialize对象上调用super

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