Learning to Cook
The third argument to R6Class() is called public and holds the user-facing functionality for the object. This argument should be a list, with names for each of its elements.
The public element of an R6 class contains the functionality available to the user. Usually it will only contain functions.
The updated pattern for creating an R6 class generator is as follows:
thing_factory <- R6Class(
"Thing",
private = list(
a_field = "a value",
another_field = 123
),
public = list(
do_something = function(x, y, z) {
# Do something here
}
)
)
Diese Übung ist Teil des Kurses
Object-Oriented Programming with S3 and R6 in R
Anleitung zur Übung
A microwave oven factory has been partially defined for you.
- Update the
publicelement of the definition to include acookmethod.- The
cookmethod is a function. - It should have one argument named
time_secondsto denote the cooking time. - In the body of the
cookmethod, you should passtime_secondstoSys.sleep()(docs), which does nothing for the allotted amount of time. - Finally, the
cookmethod shouldprint()(docs) the string"Your food is cooked!"
- The
- Create a microwave oven object called
a_microwave_ovenusing themicrowave_oven_factory'snew()method. - Call
a_microwave_oven'scook()method, for 1 second.
Interaktive Übung
Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.
# Add a cook method to the factory definition
microwave_oven_factory <- R6Class(
"MicrowaveOven",
private = list(
power_rating_watts = 800
),
public = list(
___ = ___(___) {
___
___
}
)
)
# Create microwave oven object
a_microwave_oven <- ___
# Call cook method for 1 second
___