如何使S4类从另一个S4类正确继承?

时间:2017-03-16 11:48:08

标签: r inheritance s4

我正在创建两个S4类,其中类Employee继承自另一个Person类。

这两个类的定义如下:

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

setClass("Employee", slots = list(boss="Person"))

我正在为这两个类创建一个实例

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

这很有效,但是当我尝试使用:

创建Employee实例时
john <- new("Employee", name = "John", age = 20, boss= alice)

它给出如下错误:

Error in initialize(value, ...) : 
  invalid names for slots of class “Employee”: name, age

我不能以这种方式创建对象吗?

1 个答案:

答案 0 :(得分:2)

Per nrussel的评论:

函数contains的参数setClass处理继承。您希望类Employee从类Person继承(即员工是一种特殊类型的人)。所以

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

会做到这一点。

> alice <- new("Person", name="Alice", age = 40)
> john <- new("Employee", name = "John", age = 20, boss= alice)
> john
An object of class "Employee"
Slot "boss":
An object of class "Person"
Slot "name":
[1] "Alice"

Slot "age":
[1] 40


Slot "name":
[1] "John"

Slot "age":
[1] 20