UUIDgenerate() withn a s4 class 在每个实例中生成相同的 uuid
UUIDgenerate() withn a s4 class produces the same uuid at each instance
当我在 R 中创建 S4
class 的新实例时,我希望新创建的对象具有唯一的 id
字段。我尝试通过 uuid
包中的 UUIDgenerate()
来实现它。问题是我在每个新对象实例中都获得相同的 UUID
:
library(uuid)
setClass("C",
representation=representation(
id = "character"
),
prototype = prototype(
id = UUIDgenerate(use.time = TRUE))
)
new("C")
An object of class "C"
Slot "id":
[1] "1e07d7c2-2d71-11e6-b5e1-e1f59d8ccf09"
new("C")
An object of class "C"
Slot "id":
[1] "1e07d7c2-2d71-11e6-b5e1-e1f59d8ccf09"
new("C")
An object of class "C"
Slot "id":
[1] "1e07d7c2-2d71-11e6-b5e1-e1f59d8ccf09"
在R命令行中连续调用UUIDgenerate()
每次都会产生不同的UUIDS
。
我哪里出错了?
谢谢
发生的事情是当您 运行 setClass
语句而不是当您使用 new
时评估对 UUIDgenerate
的调用。它与 UUIDgenerate
本身无关 - 例如,此 class 将仅基于 sys.time
表现相同:
setClass("D",
representation=representation(
id = "character"
),
prototype = prototype(
id = as.character(Sys.time()))
)
为了得到你想要的东西,你可以编写一个函数来创建 class "C" 的对象,如下所示:
NewC<-function(){
new("C", id=UUIDgenerate(use.time = TRUE))
}
这应该每次使用不同的 UUID 创建一个 class "C" 的新对象。
从 R 帮助列表上的 Ben Tupper 那里得到了一个非常好的解决方案。定义一个 "initialize" 函数可以更干净地解决问题:
setMethod("initialize", "C",
function(.Object){
.Object@id = UUIDgenerate(use.time = TRUE)
.Object
})
当我在 R 中创建 S4
class 的新实例时,我希望新创建的对象具有唯一的 id
字段。我尝试通过 uuid
包中的 UUIDgenerate()
来实现它。问题是我在每个新对象实例中都获得相同的 UUID
:
library(uuid)
setClass("C",
representation=representation(
id = "character"
),
prototype = prototype(
id = UUIDgenerate(use.time = TRUE))
)
new("C")
An object of class "C"
Slot "id":
[1] "1e07d7c2-2d71-11e6-b5e1-e1f59d8ccf09"
new("C")
An object of class "C"
Slot "id":
[1] "1e07d7c2-2d71-11e6-b5e1-e1f59d8ccf09"
new("C")
An object of class "C"
Slot "id":
[1] "1e07d7c2-2d71-11e6-b5e1-e1f59d8ccf09"
在R命令行中连续调用UUIDgenerate()
每次都会产生不同的UUIDS
。
我哪里出错了?
谢谢
发生的事情是当您 运行 setClass
语句而不是当您使用 new
时评估对 UUIDgenerate
的调用。它与 UUIDgenerate
本身无关 - 例如,此 class 将仅基于 sys.time
表现相同:
setClass("D",
representation=representation(
id = "character"
),
prototype = prototype(
id = as.character(Sys.time()))
)
为了得到你想要的东西,你可以编写一个函数来创建 class "C" 的对象,如下所示:
NewC<-function(){
new("C", id=UUIDgenerate(use.time = TRUE))
}
这应该每次使用不同的 UUID 创建一个 class "C" 的新对象。
从 R 帮助列表上的 Ben Tupper 那里得到了一个非常好的解决方案。定义一个 "initialize" 函数可以更干净地解决问题:
setMethod("initialize", "C",
function(.Object){
.Object@id = UUIDgenerate(use.time = TRUE)
.Object
})