控制功率
主动绑定也可用于设置私有字段。在这种情况下,绑定函数应接受一个名为 "value" 的单个参数。
创建可读/可写主动绑定的模式如下所示。
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元素中添加一个主动绑定来控制功率等级。 - 创建一个微波炉对象,并将其赋值给
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
___ <- ___