1

我有一个继承类的对象CB它继承了类A,以及每个类的方法,例如,

setClass("A", representation(a = 'numeric'))
setClass("B", representation(b = 'numeric'), contains="A")
setClass("C", representation(c = 'numeric'), contains="B")

和方法

setGeneric("toXML", function(obj, node) standardGeneric("toXML"))
setMethod("toXML", 
          signature("A", "XMLInternalElementNode"), 
          function(obj, node) addAttributes(node, a = obj@a))
setMethod("toXML", 
          signature("B", "XMLInternalElementNode"), 
          function(obj, node) addAttributes(node, b = obj@b))
setMethod("toXML", 
          signature("C", "XMLInternalElementNode"), 
          function(obj, node) addAttributes(node, c = obj@c))

也就是说,每个类都代表一个 XML 节点可能具有的属性。
我想编写一个方法(或强制),为所有匹配的类执行这些功能。

当然,按照我写的方式,做

library(XML)
obj <- new("C", a = 1, b = 2, c = 3)
toXML(obj, newXMLNode("node"))

只是返回:

<node c="3"/> 

代替

<node a="1" b="2" c="3"/> 

什么是解决这个问题的好方法?

4

1 回答 1

2

也许通过使用callNextMethod()

setGeneric("toXML", function(obj, node) standardGeneric("toXML"))
setMethod("toXML", 
          signature("A", "XMLInternalElementNode"), 
          function(obj, node) addAttributes(node, a = obj@a))
setMethod("toXML", 
          signature("B", "XMLInternalElementNode"), 
          function(obj, node) {
              node <- callNextMethod()            ## <- Line I added
              addAttributes(node, b = obj@b)
              })
setMethod("toXML", 
          signature("C", "XMLInternalElementNode"), 
          function(obj, node) {
              node <- callNextMethod()            ## <- Line I added 
              addAttributes(node, c = obj@c)
          })

## Trying it out
obj <- new("C", a = 1, b = 2, c = 3)
toXML(obj, newXMLNode("node"))
# <node a="1" b="2" c="3"/> 
于 2013-08-27T18:53:45.937 回答