You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言RC类结合自定义Example类的代码结构与调用方法咨询

R语言RC类集成自定义函数解决方案

代码组织规则

  • 小型项目可以把example()函数和RC类定义放在同一个R脚本,执行顺序为先定义example(),再定义RC类,避免调用时函数未加载
  • 大型项目可以拆分脚本:工具函数放在utils.R,RC类定义放在class.R,使用时先执行source("utils.R")再执行source("class.R")即可

基础需求实现(S3类Example输出符合要求)

你给出的期望输出可以先通过给Example这个S3类定义打印方法实现,代码调整如下:

注意:原example()函数的返回值未存储原始输入的x、y,所以新增了input_x和input_y两个字段用于打印调用参数

# 调整后的example函数
example <- function(x, y){
  tripplex <- x*3
  doubbley <- y*2
  xy_sum <- x+y
  
  Example <- list(
    trippled.x = tripplex, 
    doubbled.y = doubbley, 
    sum = xy_sum,
    # 新增原始输入存储
    input_x = x,
    input_y = y
  )
  class(Example) <- "Example"
  Example
}

# 为Example类定义专属print方法
print.Example <- function(x, ...) {
  cat("Call:\n")
  cat(paste0("x=", x$input_x, "\n", "y=", x$input_y, "\n"))
  invisible(x)
}

测试效果完全符合要求:

> object <- example(5, 10)
> print(object)
Call:
x=5
y=10
> object$trippled.x
[1] 15

功能集成到RC类的实现

如果需要把example()函数的能力封装到RC类中,调整RC类代码如下:

testClass <- setRefClass(
  "testClass",
  fields = list(
    x = "numeric",
    y = "numeric",
    # 存储example函数返回的结果
    example_result = "list"
  ),
  methods = list(
    # 初始化方法,传入x、y自动调用example计算
    initialize = function(x, y){
      .self$x <- x
      .self$y <- y
      .self$example_result <- example(x, y)
    },
    # 自定义打印方法
    show = function() {
      cat("Call:\n")
      cat(paste0("x=", .self$x, "\n", "y=", .self$y, "\n"))
    },
    # 快捷获取trippled.x的方法
    get_trippled_x = function() {
      return(.self$example_result$trippled.x)
    }
  )
)

RC类使用示例:

# 创建实例
rc_object <- testClass$new(5, 10)
# 打印实例
rc_object
# 输出:
# Call:
# x=5
# y=10

# 获取trippled.x
rc_object$get_trippled_x()
# 输出15
# 也可以直接访问存储的结果
rc_object$example_result$trippled.x

内容的提问来源于stack exchange,提问作者OLGJ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 07:06:05