extend.Rdvia a mechanism known as "parasitic inheritance".
Simply speaking this method "extends" the class of an object. What is actually
happening is that it creates an instance of class name ...className,
by taking another object and add ...className to the class
list and also add all the named values in ... as attributes.
The method should be used by the constructor of a class and nowhere else.
# Default S3 method
extend(this, ...className, ...)Returns an object of class ...className.
setConstructorS3("MyDouble", function(value=0, ...) {
extend(as.double(value), "MyDouble", ...)
})
setMethodS3("as.character", "MyDouble", function(object, ...) {
fmtstr <- attr(object, "fmtstr")
if (is.null(fmtstr))
fmtstr <- "%.6f"
sprintf(fmtstr, object)
})
#> NULL
setMethodS3("print", "MyDouble", function(object, ...) {
print(as.character(object), ...)
})
#> NULL
x <- MyDouble(3.1415926)
print(x)
#> [1] "3.141593"
x <- MyDouble(3.1415926, fmtstr="%3.2f")
print(x)
#> [1] "3.14"
attr(x, "fmtstr") <- "%e"
print(x)
#> [1] "3.141593e+00"
setConstructorS3("MyList", function(value=0, ...) {
extend(list(value=value, ...), "MyList")
})
setMethodS3("as.character", "MyList", function(object, ...) {
fmtstr <- object$fmtstr
if (is.null(fmtstr))
fmtstr <- "%.6f"
sprintf(fmtstr, object$value)
})
#> NULL
setMethodS3("print", "MyList", function(object, ...) {
print(as.character(object), ...)
})
#> NULL
x <- MyList(3.1415926)
print(x)
#> [1] "3.141593"
x <- MyList(3.1415926, fmtstr="%3.2f")
print(x)
#> [1] "3.14"
x$fmtstr <- "%e"
print(x)
#> [1] "3.141593e+00"