[英]Add methods to an R6 subclass
我開始為工作中的項目修改R6,但我無法理解以下行為。
假設我定義了一個超類Person
和一個子類PersonWithAge
:
Person <- R6Class("Person",
public = list(
name = NA,
hair = NA,
initialize = function(name, hair) {
if (!missing(name)) self$name <- name
if (!missing(hair)) self$hair <- hair
self$greet()
},
set_hair = function(val) {
self$hair <- val
},
greet = function() {
cat(paste0("Hello, my name is ", self$name, ".\n"))
}
)
)
PersonWithAge <- R6Class("PersonWithAge",
inherit = Person,
public = list(
age = NA))
如果我嘗試向PersonWithAge
子類添加新方法, PersonWithAge
出現以下錯誤:
> PersonWithAge$set("public", "set_age", function(age) self$age <<- age)
Error in self[[group]][[name]] <- value :
invalid type/length (closure/0) in vector allocation
現在,如果我使用虛擬方法定義了一個新的子類,則可以毫無問題地將新方法添加到子類中:
PersonWithHeight <- R6Class("PersonWithHeight",
inherit = Person,
public = list(
height = NA,
foo = function() print(1)
))
PersonWithHeight$set("public", "set_height", function(height) self$height <<- height)
> caitlin <- PersonWithHeight$new("Caitlin", "auburn")
Hello, my name is Caitlin.
> caitlin$set_height(165)
> caitlin
<PersonWithHeight>
Public:
foo: function
greet: function
hair: auburn
height: 165
initialize: function
name: Caitlin
set_hair: function
set_height: function
我嘗試更改R6Class
類定義中的lock
參數,但無濟於事。 會話信息是:
> sessionInfo()
R version 3.1.1 (2014-07-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
locale:
[1] LC_COLLATE=French_France.1252 LC_CTYPE=French_France.1252 LC_MONETARY=French_France.1252 LC_NUMERIC=C
[5] LC_TIME=French_France.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] R6_2.0.1
loaded via a namespace (and not attached):
[1] tools_3.1.1
在此會話信息的另一台計算機上,我也得到了相同的行為:
> sessionInfo()
R version 3.1.2 (2014-10-31)
Platform: x86_64-pc-linux-gnu (64-bit)
locale:
[1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C LC_TIME=C LC_COLLATE=C LC_MONETARY=C LC_MESSAGES=C
[7] LC_PAPER=C LC_NAME=C LC_ADDRESS=C LC_TELEPHONE=C LC_MEASUREMENT=C LC_IDENTIFICATION=C
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] R6_2.0.1
loaded via a namespace (and not attached):
[1] tools_3.1.2
我的問題如下:
編輯:好的,在查看了包的源代碼之后,我意識到,在這一行:
self[[group]][[name]] <- value
group
是public_methods
, private_methods
, public_fields
, private_fields
。 因此,我猜想在創建沒有任何公共方法的類時,由於該組實際上不存在,因此向該類添加新的公共方法失敗。
我設法通過從Winston Chang的get_nonfunctions
中utils.R
源代碼並修改get_functions
和get_nonfunctions
函數來解決該問題,以便在未找到任何函數(分別是非函數)時返回空列表,而不是NULL
。 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.