Writing the Next Method
When objects have multiple classes, you may wish to call methods for several of these classes. This is done using NextMethod()
(docs).
The S3 methods now take the form:
an_s3_method.some_class <- function(x, ...)
{
# Act on some_class, then
NextMethod("an_s3_method")
}
That is, NextMethod()
should be the last line of the method.
This exercise is part of the course
Object-Oriented Programming with S3 and R6 in R
Exercise instructions
The variable kitty
, and the generic what_am_i()
function have been predefined in your workspace.
- Inspect your workspace with
ls.str()
. - Complete the definition of the
cat
method forwhat_am_i()
. - Define a
mammal
method forwhat_am_i()
.- The arguments are the same as for the
cat
method. - Write a
message()
stating"I'm a mammal"
. - Call
NextMethod()
.
- The arguments are the same as for the
- Define a
character
method forwhat_am_i()
.- The arguments are the same as for the
cat
method. - Write a
message()
stating"I'm a character vector"
. - Don't call
NextMethod()
.
- The arguments are the same as for the
- Call
what_am_i()
withkitty
as an input, verifying that all three messages are shown.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Inspect your workspace
ls.str()
# cat method
what_am_i.cat <- function(x, ...)
{
# Write a message
___
# Call NextMethod
___
}
# mammal method
___ <- ___
# character method
___ <- ___
# Call what_am_i()
___