1

I have a ReferenceClass in R.

How can I add a method "print()" to it, which will print the values of all of the fields in the class?

4

2 回答 2

3

也许更好的实现如下

Config = setRefClass("Config",
  fields = list(    
    ConfigBool = "logical", 
    ConfigString = "character"),
  methods = list(
    ## Allow ... and callSuper for proper initialization by subclasses
    initialize = function(...) {
        callSuper(..., ConfigBool=TRUE, ConfigString="A configuration string")
        ## alterantive:
        ##    callSuper(...)
        ##    initFields(ConfigBool=TRUE, ConfigString="A configuration string")
    },
    ## Implement 'show' method for automatic display
    show = function() {
        flds <- getRefClass()$fields()
        cat("* Fields\n")
        for (fld in names(flds))  # iterate over flds, rather than index of flds
            cat('  ', fld,': ', .self[[fld]], '\n', sep="")
    })
  )

下面说明了Config构造函数的使用(不需要调用'new')和自动调用'show'

> Config()
* Fields
  ConfigBool: TRUE
  ConfigString: A configuration string
于 2014-05-04T17:18:29.147 回答
2

在 R 控制台中运行以下演示:

# Reference Class to store configuration

Config <- setRefClass("Config",
  fields = list(    
    ConfigBool = "logical", 
    ConfigString = "character"
    ),
    methods = list(
        # Constructor.
        initialize = function(x) {
            ConfigBool <<- TRUE
            ConfigString <<- "A configuration string"
        },
        # Print the values of all of the fields used in this class.
        print = function(values) {
            cat("* Fields\n")
            fieldList <- names(.refClassDef@fieldClasses)           
            for(fi in fieldList)
            {
                variableName = fi
                variableValue = field(fi)
                cat('  ',variableName,': ',variableValue,'\n',sep="")           
            }
        }
  )
)

config <- Config$new()
config
config$print()

---test code---

# Demos how to print the fields of the class using built-in default "show()" function.
> config$show()
Reference class object of class "Config"
Field "ConfigBool":
[1] TRUE
Field "ConfigString":
[1] "A configuration string"

# Omitting the "show()" function has the same result, as show() is called by default.
> config
Reference class object of class "Config"
Field "ConfigBool":
[1] TRUE
Field "ConfigString":
[1] "A configuration string"

# Demos how to print the fields of the class using our own custom "print" function.
> config$print()
* Fields
  ConfigBool: TRUE
  ConfigString: A configuration string

此外,键入以下内容会显示所有 ReferenceClass 中包含的默认“show”函数的源代码:

config$show
于 2014-05-04T15:00:15.090 回答