为什么S4继承在环境之间丢失?

时间:2021-02-01 23:21:47

Suppose I have a class MyClass defined as follows:

假设我有一个类MyClass定义如下:

setClass(
    "MyClass", 
    slots = c(message = "character"), 
    validity = function(object) { T })

If I create an instance of it, inherits works as expected:

如果我创建它的实例,则继承其预期的工作:

myInstance <- new("MyClass", message = "Hello")

inherits(myInstance, "MyClass")

TRUE

真正的

However, it doesn't work after I put the instance into an environment and bring it back again:

但是,当我把这个实例放到一个环境中,并把它重新放回来之后,它就不起作用了:

e <- new.env(hash = T, parent = emptyenv())

assign("MyInstance", myInstance, envir = e)

inherits(mget("MyInstance", envir = e), "MyClass")

FALSE

But the data is still there:

但数据仍然存在:

mget("MyInstance", envir = e)

$MyInstance An object of class "MyClass" Slot "message": [1] "Hello"

$MyInstance一个类的对象“MyClass”插槽“消息”:[1]“Hello”

How can I tell R to maintain my S4 classes even when saving and loading instances between environments?

即使在环境之间保存和加载实例时,我如何告诉R维护我的S4类?

1 个解决方案

#1


4  

mget returns a named list of the objects requested. You're actually examining the list. To examine the object you need to extract it from the output of mget. Alternatively just use get which returns just the object of interest.

mget返回被请求对象的命名列表。你实际上是在检查列表。要检查对象,您需要从mget的输出中提取它。也可以使用get,它只返回感兴趣的对象。

mget is useful when requesting a bunch of objects but if you just want one then get is just fine.

mget在请求一堆对象时很有用,但是如果你只想要一个对象,那么它就可以。

#1


4  

mget returns a named list of the objects requested. You're actually examining the list. To examine the object you need to extract it from the output of mget. Alternatively just use get which returns just the object of interest.

mget返回被请求对象的命名列表。你实际上是在检查列表。要检查对象,您需要从mget的输出中提取它。也可以使用get,它只返回感兴趣的对象。

mget is useful when requesting a bunch of objects but if you just want one then get is just fine.

mget在请求一堆对象时很有用,但是如果你只想要一个对象,那么它就可以。