oop - Is there a way to initialize a S4 object so that another object will be returned? -
i have class hierarchy superclass fb
of no objects should exist (i tried virtual classes ran in problem can not initialize objects virtual classes). further, have 2 sub classes (foo
, bar
) same slots. want make new object, using initialize method superclass returns object of 1 of subclasses based on value:
setclass("fb", representation( x = "numeric")) setclass("foo", contains = "fb") setclass("bar", contains = "fb") setmethod("initialize", "fb", function(.object, x) { if (x < 5) class(.object) <- "foo" else class(.object) <- "bar" .object@x <- x .object }) > new("fb", x = 3) error in initialize(value, ...) : initialize method returned object of class "foo" instead of required class "fb"
obviously (and reasons) r disallows that. there way achieve want within method , not using if-else construct when create new object?
s4 helps color within lines. fb
class should virtual, initialize
method shouldn't change class of .object
. might write function fb
conditional instantiation.
setclass("fb", representation( x = "numeric", "virtual")) setclass("foo", contains = "fb") setclass("bar", contains = "fb") fb <- function(x) { if (x < 5) new("foo", x=x) else new("bar", x=x) }
fb
constructor, more convenient user, , separates interface class hierarchy implementation considered thing.
and it's worth implicit constraint on s4 initialize
methods new("foo")
(invoking new
class name no additional arguments) must work (otherwise there failures when try extend foo). paradigm initialize method along lines of
setmethod(initialize, "foo", function(.object, ..., x=1) { .object <- callnextmethod(.object, ...) .object@x <- x .object })
though (as in case, initialize
doing slot assignment) there no need initialize method @ all. note use of ...
, positioning of x
(requiring argument named in corresponding call new
) , use of default value.
Comments
Post a Comment