Commençons par le début
Il existe une méthode publique spéciale nommée initialize() (notez l’orthographe américaine). Elle n’est pas appelée directement par l’utilisateur. Elle est appelée automatiquement lors de la création d’un objet, c’est-à-dire quand l’utilisateur appelle new().
initialize() vous permet de définir les valeurs des champs privés lorsque vous créez 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 renvoie TRUE si un argument n’a pas été passé lors de l’appel.
Les arguments de la méthode new() de la fabrique sont transmis à initialize().
a_thing <- thing_factory$new(
a_field = "a different value",
another_field = 456
)
Cet exercice fait partie du cours
Programmation orientée objet avec S3 et R6 en R
Instructions
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 une 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 cet exemple de code.
# 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 <- ___