如何使用继承向S3类添加属性?

时间:2018-03-02 19:32:40

标签: r oop

我有一个类构造函数:

particle <- function(Charge=0, Spin=0, Energy=0, P=c(0,0,0), X=c(0,0,0), M=0){
    structure(list(), class='particle', charge=Charge, spin=Spin, energy=Energy,
              p=P, x=X, m=M)
}

我想创建一个继承粒子类的类变量的类,并添加一个额外的变量composite

fermion <- function(Spin=0.5){
    particle(Spin=0.5)
    composite = TRUE
}

如果我现在使用我的课程......

> f <- fermion(1.5)
> f
$composite
[1] TRUE

这不是我想要的。相反,我想要像:

> f
list()
attr(,"class")
[1] "particle"
attr(,"charge")
[1] 0
attr(,"spin")
[1] 0.5
attr(,"energy")
[1] 0
attr(,"p")
[1] 0 0 0
attr(,"x")
[1] 0 0 0
attr(,"m")
[1] 0
attr(,"composite")
[1] TRUE

问题:如果我从另一个类继承了类的属性,我该如何添加一个新属性?在Python中,它将类似于self.composite=TRUE

1 个答案:

答案 0 :(得分:2)

这将创建一个类c("fermion", "particle")的对象,其中包含所有粒子属性和复合:

fermion <- function(Spin=0.5, ...){
    structure(particle(Spin=Spin, ...), class = c("fermion", "particle"), composite = TRUE)
}

# test
str(fermion())

,并提供:

 list()
 - attr(*, "class")= chr [1:2] "fermion" "particle"
 - attr(*, "charge")= num 0
 - attr(*, "spin")= num 0.5
 - attr(*, "energy")= num 0
 - attr(*, "p")= num [1:3] 0 0 0
 - attr(*, "x")= num [1:3] 0 0 0
 - attr(*, "m")= num 0
 - attr(*, "composite")= logi TRUE

请注意,如果您只想将composite = TRUE添加到单个"particle"对象并将其Spin更改为0.5而不是创建一个全新的类,那么您可以这样做:

p <- particle()
p2 <- structure(p, Spin = 0.5, composite = TRUE)