Comece agoraComece grátis

Controle a potência

Active bindings também podem ser usados para definir campos privados. Nesse caso, a função de binding deve aceitar um único argumento, chamado "value".

O padrão para criar um active binding de leitura/gravação é o seguinte.

thing_factory <- R6Class(
  "Thing",
  private = list(
    ..a_field = "a value"
  ),
  active = list(
    a_field = function(value) {
      if(missing(value)) {
        private$..a_field
      } else {
        assert_is_a_string(value) # ou outra asserção
        private$..a_field <- value
      }
    }
  )
)

Os valores são atribuídos como se o binding fosse uma variável de dados, não uma função.

a_thing <- thing_factory$new()
a_thing$a_field <- "a new value" # não a_thing$a_field("a new value")

Este exercicio faz parte do curso

Programação Orientada a Objetos com S3 e R6 em R

Ver curso

Instruções do exercicio

Uma classe de forno de micro-ondas foi parcialmente definida para você.

  • Estenda a definição da classe do micro-ondas para incluir um elemento active.
  • Adicione um active binding ao elemento active para controlar o nível de potência.
    • A função deve se chamar power_level_watts.
    • Ela deve aceitar um único argumento chamado value.
    • A variável privada para obter/definir é ..power_level_watts.
    • Use assert_is_a_number() (docs) para verificar se value é um único número.
    • Use assert_all_are_in_closed_range() (docs) para verificar se value está entre 0 e ..power_rating_watts.
  • Crie um objeto de micro-ondas e atribua-o a a_microwave_oven.
  • Obtenha o nível de potência.
  • Tente definir o nível de potência para o valor "400", como string.
  • Tente definir o nível de potência para 1600.
  • Defina o nível de potência para 400.

exercicio interativo prático

Tente este exercicio completando este código de exemplo.

# Add a binding for power rating
microwave_oven_factory <- R6Class(
  "MicrowaveOven",
  private = list(
    ..power_rating_watts = 800,
    ..power_level_watts = 800
  ),
  # Add active list containing an active binding
  ___ = ___(
    ___ = ___(___) {
      if(missing(___)) {
        # Return the private value
        ___
      } else {
        # Assert that value is a number
        ___
        # Assert that value is in a closed range from 0 to power rating
        ___
        # Set the private power level to value
        ___ <- ___
      }
    }
  )
)

# Make a microwave 
a_microwave_oven <- ___

# Get the power level
___

# Try to set the power level to "400"
___ <- ___

# Try to set the power level to 1600 watts
___ <- ___

# Set the power level to 400 watts
___ <- ___
Editar e Executar Código