1

RにReferenceClassがあります。

クラス内のすべてのフィールドの値を出力するメソッド「print()」を追加するにはどうすればよいですか?

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

さらに、次のように入力すると、すべての ReferenceClasses に含まれるデフォルトの「show」関数のソース コードが表示されます。

config$show
于 2014-05-04T15:00:15.090 に答える