LoslegenKostenlos loslegen

Read the Rating

The data stored by an R6 object is deliberately hidden away from the user by keeping it in the private element. This is the principle of encapsulation.

If you want to provide access to any of the data values, you can use an active binding. These are functions that behave like variables.

Active bindings are stored in the active element of an R6 object. To create an active binding to get a private data field (i.e. a "read-only" binding), you create a function with no arguments that simply returns the private element.

The pattern for creating a read-only active binding is as follows:

thing_factory <- R6Class(
  "Thing",
  private = list(
    ..a_field = "a value"
  ),
  active = list(
    a_field = function() {
      private$..a_field
    }
  )
)

The active binding is called like a data variable, not a function.

a_thing <- thing_factory$new()
a_thing$a_field   # not a_thing$a_field()

Diese Übung ist Teil des Kurses

Object-Oriented Programming with S3 and R6 in R

Kurs anzeigen

Anleitung zur Übung

A microwave oven factory has been partially defined for you.

  • Update the definition to include a read-only active binding to get the power rating.
    • The active binding should be named power_rating_watts.
    • This is defined as a function, with no arguments.
    • The body should simply return the private ..power_rating_watts field.
  • Create a microwave oven object and assign it to a_microwave_oven.
  • Read its power rating.

Interaktive Übung

Versuche dich an dieser Übung, indem du diesen Beispielcode vervollständigst.

# Add a binding for power rating
microwave_oven_factory <- R6Class(
  "MicrowaveOven",
  private = list(
    ..power_rating_watts = 800
  ),
  active = list(
    # Add the binding here
    ___ = ___

    
  )
)

# Make a microwave 
a_microwave_oven <- ___

# Get the power rating
___
Code bearbeiten und ausführen