R S3 Inheritance
A class vector gives a value more than one class name, in order. Method lookup tries the names in that order until it finds a matching method.
NextMethod runs the parent method
describe.savings prints its own line first. NextMethod then runs describe.wallet for the same value.
describe <- function(x, ...) {
UseMethod("describe")
}
describe.wallet <- function(x, ...) {
cat("A wallet holding", x$balance, "coins\n")
}
describe.savings <- function(x, ...) {
cat("Savings first\n")
NextMethod()
}
savings <- list(balance = 100)
class(savings) <- c("savings", "wallet")
describe(savings)Check the class vector
The class vector holds savings first and wallet second. inherits gives TRUE for both names and FALSE for a name that is not in the vector.
savings <- list(balance = 100)
class(savings) <- c("savings", "wallet")
print(class(savings))
print(inherits(savings, "wallet"))
print(inherits(savings, "savings"))
print(inherits(savings, "card"))Fall back to the next class
This script defines no savings method at all. Lookup moves past savings and runs the wallet method.
describe <- function(x, ...) {
UseMethod("describe")
}
describe.wallet <- function(x, ...) {
cat("A wallet holding", x$balance, "coins\n")
}
describe.default <- function(x, ...) {
cat("A plain value\n")
}
savings <- list(balance = 30)
class(savings) <- c("savings", "wallet")
describe(savings)Example
describe <- function(x, ...) {
UseMethod("describe")
}
describe.wallet <- function(x, ...) {
cat("A wallet holding", x$balance, "coins\n")
}
describe.savings <- function(x, ...) {
cat("Savings first\n")
NextMethod()
}
savings <- list(balance = 40)
class(savings) <- c("savings", "wallet")
describe(savings)
print(inherits(savings, "wallet"))Key points
- The first name in a class vector is the most specific class.
- A method for an early name runs before a method for a later name.
- NextMethod inside a method runs the method for the next name in the vector.
- A value with no method for its first name falls back to a method for a later name.
- inherits reports TRUE when a name sits anywhere in the class vector of a value.
- inherits reports FALSE when the name is not in the class vector.
In this example the savings method prints its own line and NextMethod runs the wallet method after it. inherits then confirms that wallet sits in the class vector of the savings value.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท rdrr.io R Snippets
Exercise
What does NextMethod do inside a method?