我有一个对象C
,它继承了继承类B
的类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"/>
有什么好办法可以解决这个问题?
答案 0 :(得分: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"/>