我正在尝试在R6中创建一个从其父类继承一个函数的类。但是,该函数依赖于在子类中覆盖的其他“辅助”函数。
当我调用父函数时,我希望它使用父类中的辅助函数,而不是子类中的重写函数。
以下是我的代码工作方式的模型:
ParentClass <- R6Class(
public = list(
helper_fn = function() { print("Parent helper.") },
main_fn = function() { self$helper_fn() }
}
)
)
ChildClass <- R6Class(
inherit = ParentClass,
public = list(
helper_fn = function() { print("Child helper.") },
main_fn = function() { super$main_fn() }
)
)
预期的行为是打印“父母帮助者”。但是当child_class
调用父级的main_fn
时,它将使用child_class
中的覆盖函数。
child_class <- ChildClass$new()
child_class$main_fn()
# prints "Parent helper."
是否可以避免这种情况?还是这仅仅是重写功能的原理?
答案 0 :(得分:0)
我可能无法提供解决方案,但看起来是因为父级的 main_fn
在 self
上调用了一个函数 - 而 R 将其定向到子级的实例而不是父级的实例中。< /p>
您可以尝试从父级继承 helper_fn
并将子级的助手命名为不同的名称,如 childHelper_fn
,如果这适合您尝试执行的操作。