Commençons par l'essentiel
Il existe une méthode publique spéciale nommée initialize() (notez l'orthographe en anglais américain). Elle n'est pas appelée directement par l'utilisateur. Elle est plutôt appelée automatiquement lors de la création d'un objet, c'est‑à‑dire lorsque l'utilisateur appelle new().
initialize() vous permet de définir les valeurs des champs privés au moment de créer un objet R6. Le modèle d'une fonction initialize() est le suivant :
thing_factory <- R6Class(
"Thing",
private = list(
a_field = "a value",
another_field = 123
),
public = list(
initialize = function(a_field, another_field) {
if(!missing(a_field)) {
private$a_field <- a_field
}
if(!missing(another_field)) {
private$another_field <- another_field
}
}
)
)
Remarquez l'utilisation de missing() (docs). Cette fonction retourne TRUE si un argument n'a pas été fourni à l'appel de la fonction.
Les arguments passés à la méthode new() de la fabrique sont transmis à initialize().
a_thing <- thing_factory$new(
a_field = "a different value",
another_field = 456
)
Cette activité fait partie du cours
Programmation orientée objet avec S3 et R6 en R
Instructions de l’exercice
Une fabrique de fours à micro-ondes a été partiellement définie pour vous.
- Ajoutez une méthode publique nommée
initialize(). Elle doit permettre à l'utilisateur de définir les champspower_rating_wattsetdoor_is_openlors de la création de l'objet.- Les arguments doivent être
power_rating_wattsetdoor_is_open. - Dans le corps de la méthode
initialize(), pour chaque argument, s'il n'est pasmissing()(docs), alors le champ privé correspondant doit être défini.
- Les arguments doivent être
- Créez un objet micro-ondes avec une puissance nominale de
650watts et la porte ouverte.- Appelez la méthode
new()demicrowave_oven_factory. - Passez les arguments
power_rating_watts = 650etdoor_is_open = TRUEànew(). - Assignez le résultat à
a_microwave_oven.
- Appelez la méthode
Exercice interactif pratique
Essayez cet exercice en complétant ce code d’exemple.
# Add an initialize method
microwave_oven_factory <- R6Class(
"MicrowaveOven",
private = list(
power_rating_watts = 800,
door_is_open = FALSE
),
public = list(
cook = function(time_seconds) {
Sys.sleep(time_seconds)
print("Your food is cooked!")
},
open_door = function() {
private$door_is_open <- TRUE
},
close_door = function() {
private$door_is_open <- FALSE
},
# Add initialize() method here
___ = ___(___, ___) {
if(!missing(power_rating_watts)) {
private$power_rating_watts <- power_rating_watts
}
___
}
)
)
# Make a microwave
a_microwave_oven <- ___