1

ann <- Person$new("Ann", "black")

在上面的例子中(来自这个 Introduction),我如何得到“ann”?

例如,我需要一个返回“ann”的方法 ann$getName。

4

1 回答 1

0

我正在尝试做同样的事情,所以也许我可以澄清这个问题。目标(对我来说)是给班级的用户一些反馈。像这样的东西:

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

    do_something_very_long=function(){
      whoami <- self$getInstanceName() ## $getInstanceName() is the method I need to write !
      message(paste("Please wait, processing object",whoami))
      # Do a very long calculation... 
     }
  )
)

然后我会在一个脚本中运行它,它会做类似的事情

#File batch_processing.R
first_in_line<-Person$new("Alice","Black")
next_customer<-Person$new("Bob","Red")
VIP<-Person$new("Charlie","Brown")
# etc ...

first_in_line$do_something_very_long()
next_customer$do_something_very_long()
VIP$do_something_very_long()
# etc ...

所以,我的(名义上的)用户将启动 batch_processing.R,也许与

$ R ~/batch_processing.R 

或者

R> source("batch_processing.R")

并在脚本运行时观看没有发生太多事情。因此,我想要一些反馈,以便当用户喝完咖啡回来时,他可以查看屏幕并看到计算机正忙于处理 VIP 或 next_customer。

显然 - 一种方法是为每个对象显式地赋予唯一标识符(在这种情况下为 $name )。然而,在我的实际应用案例中,这不是很有意义,或者会重复对象名称(“模型 1”、“模型 2”...),这有点浪费!

于 2020-07-20T05:16:15.960 回答