【发布时间】:2014-09-15 19:10:51
【问题描述】:
假设我想定义两个类,Sentence 和 Word。每个词对象都有一个字符串和一个词性(pos)。每个句子都包含一定数量的单词,并有一个额外的数据槽。
Word 类易于定义。
wordSlots <- list(word = "character", pos = "character")
wordProto <- list(word = "", pos = "")
setClass("Word", slots = wordSlots, prototype = wordProto)
Word <- function(word, pos) new("Word", word=word, pos=pos)
现在我想创建一个Sentence 类,它可以包含一些Words 和一些数字数据。
如果我这样定义Sentence 类:
sentenceSlots <- list(words = "Word", stats = "numeric")
sentenceProto <- list(words = Word(), stats = 0)
setClass("Sentence", slots = sentenceSlots, prototype = sentenceProto)
那么这个句子只能包含一个单词。我显然可以用很多槽来定义它,每个单词一个,但是长度会受到限制。
但是,如果我这样定义 Sentence 类:
sentenceSlots <- list(words = "list", stats = "numeric")
sentenceProto <- list(words = list(Word()), stats = 0)
setClass("Sentence", slots = sentenceSlots, prototype = sentenceProto)
它可以包含任意数量的单词,但插槽 words 可以包含不属于 Word 类的对象。
有没有办法做到这一点?这类似于 C++ 中您可以拥有相同类型对象的向量。
【问题讨论】:
-
我认为我之前的建议(已删除)很好。在句子中将其更改为单词向量而不是单词列表。我在 R 中没有做太多 OO 编程,但我认为这应该可行。
-
它不会将它解释为一个向量,而是一个列表。使用
words="vector"和x <- new("Sentence"),x@words <- c(Word(),Word(),3)不会导致错误并使x@words成为一个列表。 -
可以理解吧?因为您有两个 Word 类型的元素和一个数字类型的元素?它甚至会在设置发生之前被强制执行。 3是否对应句子对象中的stats?
-
在我看来,您希望通过 x@words
-
一种变通方法是检查
Sentence构造函数中列表组件的类。例如,请参阅sp包的Polygons构造函数。然后您可以重新定义@<-运算符以避免用户设置word插槽绕过您的约束。