Lendo e escrevendo com active bindings

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

Richie Cotton

Data Evangelist at DataCamp

ch3_3-getting-and-setting-with-active-bindings.003.png

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

 

 

     getting = ler o campo de dados

     setting = escrever no campo de dados

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

Active Bindings

 

 

     definidos como funções

     acessados como variáveis de dados

Programação Orientada a Objetos com S3 e R6 em R
thing_factory <- R6Class(
  "Thing",
  private = list(
    ..a_field = "a value",
    ..another_field = 123
  ),
  active = list(

a_field = function() {
if(is.na(private$..a_field)) { return("a missing value") }
private$..a_field
},
another_field = function(value) {
if(missing(value)) { private$..another_field } else {
assert_is_a_number(value)
private$..another_field <- value }
}
) )
Programação Orientada a Objetos com S3 e R6 em R
a_thing <- thing_factory$new()

a_thing$a_field
"a value"
a_thing$a_field <- "a new value"
Error in (function (value)  : a_field is read-only.
Programação Orientada a Objetos com S3 e R6 em R

 

a_thing$another_field <- 456
a_thing$another_field <- "456"
Error in (function (value) : is_a_number : 
value is not of class 'numeric'; it has class 'character'.
Programação Orientada a Objetos com S3 e R6 em R

Resumo

  • Controle o acesso privado com active bindings
  • Definidos como funções
  • Acessados como dados
Programação Orientada a Objetos com S3 e R6 em R

Vamos praticar!

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

Preparing Video For Download...