開始使用免費開始

控制功率

Active 綁定也可以用來設定私有欄位。在這種情況下,綁定函式應該接受一個名為「value」的單一引數。

建立可讀寫的 active 綁定的範式如下。

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) # 或其他斷言
        private$..a_field <- value
      }
    }
  )
)

指定值時,就把綁定當作資料變數而不是函式。

a_thing <- thing_factory$new()
a_thing$a_field <- "a new value" # 不是 a_thing$a_field("a new value")

本練習屬於課程

在 R 中使用 S3 與 R6 的物件導向程式設計

檢視課程

練習說明

已為你部分定義了一個微波爐類別。

  • 擴充微波爐類別的定義,加入一個 active 清單元素。
  • active 元素中新增一個用來控制功率等級的 active 綁定。
    • 這個函式名稱應為 power_level_watts
    • 它應該接受一個名為 value 的單一引數。
    • 要讀取/設定的私有變數名稱是 ..power_level_watts
    • 使用 assert_is_a_number()文件)檢查 value 是否為單一數值。
    • 使用 assert_all_are_in_closed_range()文件)檢查 value 是否介於 0..power_rating_watts 之間。
  • 建立一個微波爐物件,指定給 a_microwave_oven
  • 讀取功率等級。
  • 嘗試將功率等級設定為字串 "400"
  • 嘗試將功率等級設定為 1600
  • 將功率等級設定為 400

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# 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
___ <- ___
編輯並執行程式碼