与S4类的多个继承者进行交互

时间:2019-05-09 15:20:15

标签: r s4

我对R中的面向对象程序设计还很陌生,我正在尝试理解继承。我有一个问题,我需要能够看到所有从父类对象继承的类对象,而且我不确定该怎么做。

我可以使用在线资源中的一个常见示例来演示我的问题:

setClass("Person",
  slots = list(name = "character", age = "numeric"))
setClass("Employee",
  slots = list(boss = "Person"),
  contains = "Person")

## Create boss Alice
alice <- new("Person", name = "Alice", age = 40)

## Create Alice's subordinates
john <- new("Employee", name = "John", age = 20, boss = alice)
bob <- new("Employee", name = "John", age = 26, boss = alice)
jane <- new("Employee", name = "Jane", age = 22, boss = alice)

我现在已经创建了三名员工,每个人都有相同的老板:爱丽丝。但是,当我查询Alice的类对象时,无法看到她的雇员是谁。我知道这不是类对象的工作方式,但是鉴于我的目的,我需要能够看到爱丽丝所有员工的人,为此我将使用的最佳解决方案是什么? >

此外,我希望能够遍历Alice的每个下属,然后提取并与他们的每个Employee类对象进行交互。

这是我想做的事的一个例子:

myFunction(funClassObj) {
  print(paste("Subordinate name: ", funClassObj@name))
  print(paste("Subordinate age: ", funClassObj@age))
}

for(subClassObj in alice@subordinates) {
  myFunction(subClassObj)
}

我一直无法做到这一点,我们将不胜感激。

1 个答案:

答案 0 :(得分:0)

编辑:您可以替代地使用雇主并将其链接到雇员:

setMethod("Bosses","Employee",function(object) object@boss)
setIs("Employee","Person",
      coerce = function(old) old@boss,
      replace =  function(old,new_val){
        old@name<-new_val
        old
      })
setMethod("Bosses","Person", function(object) object@boss)
Bosses(john)
An object of class "Person"
Slot "name":
[1] "Alice"

Slot "age":
[1] 40

也许有人有更好的答案,这是替代方法:

setGeneric("Bosses",function(object) standardGeneric("Bosses"))
setMethod("Bosses","Employee",function(object) object@boss)
my_employees<-list(john,bob,jane)
lapply(my_employees,Bosses) #Maybe implement this in s4?

结果:

[[1]]
An object of class "Person"
Slot "name":
[1] "Alice"

Slot "age":
[1] 40


[[2]]
An object of class "Person"
Slot "name":
[1] "Alice"

Slot "age":
[1] 40


[[3]]
An object of class "Person"
Slot "name":
[1] "Alice"

Slot "age":
[1] 40