在R6中从超类转换为继承的类

时间:2016-11-03 10:49:50

标签: r inheritance r6

让我说我有

library(R6)

Person <- R6Class("Person",
              public = list(
                name = NULL,
                hair = NULL,
                initialize = function(name = NA, hair = NA) {
                  self$name <- name
                  self$hair <- hair
                  self$greet()
                },
                set_hair = function(val) {
                  self$hair <- val
                },
                greet = function() {
                  cat(paste0("Hello, my name is ", self$name, ".\n"))
                }
              )
)

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

然后在R控制台上我说,

newobject <- Person("Ann", "black")
Hello, my name is Ann.

有没有办法让我现在可以使用上面的对象而无需在继承的对象中重用名称或重写代码

e.g。我不想做

inheritObject <- PersonWithSurname$new("Ann", "Doe", "black")
Hello, my name is Ann.

因为我正在重复“安”和“黑”,理想情况下我只想要

inheritObject <- PersonWithSurname$new("Doe")
Hello, my name is Ann.

它会保留所有属性。

提前致谢。

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

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

如您所见,我允许您的构造函数提供Person对象,而不是定义名称的character。试一试:

inheritObject<-PersonWithSurname$new(newobject,"Doe")
#Hello, my name is Ann.