我开始为工作中的项目修改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$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
我尝试更改类定义中的lock
参数,R6Class
但无济于事。会话信息是:
> 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_functions
和get_nonfunctions
函数,utils.R
以使它们返回一个空列表,而不是NULL
在找不到任何函数(分别是非函数)的情况下。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句