简体   繁体   English

R6类中的静态方法

[英]Static methods in R6 classes

Is there a way to add static methods to R6 classes? 有没有办法向R6类添加静态方法? For example, a function that can be called like 例如,可以调用的函数

MyClass$method()

Instead of 代替

myinstance <- MyClass$new()
myinstance$method()

I'm not an expert on R6 but since every R6 class is an environment, you can add anything you want to this environment. 我不是R6的专家,但由于每个R6类都是一个环境,你可以在这个环境中添加你想要的任何东西。

Like: 喜欢:

MyClass$my_static_method <- function(x) { x + 2}
MyClass$my_static_method(1)
#[1] 3

But the method will not work on the instance of the class : 但该方法不适用于该类的实例

instance1 <- MyClass$new()
instance1$my_static_method(1)
# Error: attempt to apply non-function

You should be careful with the existing objects in the class environment. 您应该小心类环境中的现有对象。 To see what is already defined use ls(MyClass) 要查看已定义的内容,请使用ls(MyClass)

I have used a workaround for the solution. 我使用了解决方案的解决方法。 You can access the methods without creating the instance by calling MyClass$public_methods$my_static_method() . 您可以通过调用MyClass$public_methods$my_static_method()来访问方法而无需创建实例。 To restrict the calls without the instance, I have made self as an argument in all of the methods. 为了限制没有实例的调用,我在所有方法中都将self作为参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM