0

オブジェクトを同時に更新し、値を返すメソッドを 1 つ作成する必要があります。S4クラスでこれを行う方法があるかどうか知りたいです。このコンテキストは、秘密鍵がわかっている場合にのみ各要素にアクセスできるリストを生成する S4 クラスを作成しようとしているということです。これを行うには、リストとキー リストの長さを同時に更新し、インデックス キー ペアを返すメソッド getNewSlot が必要です。コードを以下に示します。

setClass("ProtectedRObjectList", 
  representation(objectList = "list", keys = "character", length = "numeric"))

setGeneric(
  name = "getNewSlot",
  def = function(object,value){standardGeneric("getNewSlot")})

setMethod(
  f = "getNewSlot", 
  signature = "ProtectedRObjectList", 
  definition = function(object){
    if(length(object@length)==0)
    {
      #initial case
      object@length <- 0;
    }

    #update list length and generate random key
    object@length<-object@length + 1;
    object@keys[object@length]<-paste(sample(c(letters, LETTERS), 15, replace =TRUE), collapse = "");
    #return "index, key" pair
    return(list("index" = object@length, "key" = object@keys[object@length]))
  }
)

このメソッドの出力は次のとおりです。ご覧のとおり、コードは目的の「インデックス、キー」のペアを返しますが、オブジェクトは更新しません。

> thisObj<-new("ProtectedRObjectList")
> thisObj
An object of class "ProtectedRObjectList"
Slot "objectList":
list()

Slot "keys":
character(0)

Slot "length":
numeric(0)

> output<-getNewSlot(thisObj)
> output
$index
[1] 1

$key
[1] "cjdkDvAaNjvVKdw"

> thisObj
An object of class "ProtectedRObjectList"
Slot "objectList":
list()

Slot "keys":
character(0)

Slot "length":
numeric(0)
4

1 に答える 1

2

これはあなたが望むものではないかもしれませんが、参照渡し関数呼び出しが必要なので、おそらくR5クラスがあなたの目的に適しています。

R5クラスをS4クラスから書き直すのは簡単です(そしてR5での実装はS4での実装よりも簡単です)。定義は次のとおりです(名前が重複しているため、フィールドがに置き換えられていることに
注意してください)。lengthlen

ProtectedRObjectList <- setRefClass(
  "ProtectedRObjectList", 
  fields = list(objectList = "list", keys = "character", len = "numeric"),
  methods=list(
    getNewSlot = function(){
      if(length(len)==0)
      {
        #initial case
        len <<- 0;
      }
      #update list length and generate random key
      len<<-len + 1;
      keys[len]<<-paste(sample(c(letters, LETTERS), 15, replace =TRUE), collapse = "");
      #return "index, key" pair
      return(list("index" = len, "key" = keys[len]))
    }
  )
)

と使用法:

> thisObj<-ProtectedRObjectList$new()
> thisObj
An object of class "ProtectedRObjectList"
<environment: 0x116207c30>
> thisObj$len
numeric(0)
> thisObj$keys
character(0)
> 
> output<-thisObj$getNewSlot()
> output
$index
[1] 1

$key
[1] "GeCyCTdIflcYFbE"

> 
> thisObj$len
[1] 1
> thisObj$keys
[1] "GeCyCTdIflcYFbE"
于 2011-03-26T01:09:52.097 に答える