1

In large projects I sometime want to have a standardized and rigid data 'object' such that any function of that data may confidently assume numerous properties of the object with no more than an assertion that the object is of the expected class. So I'm very happy to have discovered R6 classes, which seem to allow this by providing 'private' elements as follows:

library('R6')
Data = R6::R6Class("Data", 
    private = list(x = NA, y = pi),
    public = list(
        initialize = function(x, y) {
            private$x = x
        },
        get = function(attribute) return(private[[attribute]])
    )
)

data = Data$new(x = 5)
data$get('x')
data$get('y')

This get function is a hack. What I really want is for the attributes of data to be accessible simply as data$x or data[['x']] while still having the tamper-proof qualities of private variables. Is there a better way to achieve this?

4

1 回答 1

1

我将简要总结一下我在这里学到的东西。该base::lockBinding函数在这里适用,因为 R6 类本质上是一个环境:

library('R6')
Data = R6::R6Class("Data", 
    public = list(
        x = NA,
        y = pi,
        initialize = function(x) {
            self$x = x
            lockBinding("x", self)
            lockBinding("y", self)
        }
    )
)

data = Data$new(x = 5)
data$x
data$y

由于xy被锁定,因此data$x = 5会根据需要引发错误。

于 2018-05-08T17:16:12.690 回答