1 minute read

Exercises����������������������������������������������������������������������������������������������������������������������

Chapter 10 ■ ObjeCt Oriented prOgramming

## 9 1.0121812 0.39513461 ## 10 -1.7562905 -0.72161442 ## ## $mean ## [,1] ## (Intercept) 0.2063805 ## x 2.5671043 ## ## $covar ## (Intercept) x ## (Intercept) 0.07399730 -0.01223202 ## x -0.01223202 0.05824769 ## ## attr(,"class") ## [1] "blm"

Advertisement

The only difference from before is that it has added information about the "class" attribute toward the end. It still just prints everything that is contained in the object. This is because we haven’t told it to treat any object of class blm any differently yet.

Polymorphic Functions

The print function is a polymorphic function. This means that what happens when it is called depends on the class of its first parameter. When we call print, R will get the class of the object, let’s say it is blm as in our case, and see if it can find a function named print.blm. If it can, then it will call this function with the parameters you called print with. If it cannot, it will instead try to find the function print.default and call that.

We haven’t defined a print function for the class blm, so we saw the output of the default print function instead.

Let’s try to define a blm-specific print function.

print.blm <- function(x, ...) { print(x$formula)

Here, we just tell it to print the formula we used for specifying the model rather than the full collection of data we put in the list.

If we print the model now, this is what happens:

model ## y ~ x

That is how easy it is to provide your own class-specific print function. And that is how easy it is to define your own class-specific polymorphic function in general. You just take the function name and append .classname to it, and if you define a function with that name, then that function will be called when you call a polymorphic function on an object with that class.

One thing you do have to be careful about, though, is the interface to the function. By that I mean the parameters the function takes (and their order). Each polymorphic function takes some arguments. You can see which by checking the function documentation.

?print

261

This article is from: