R:如何在方法中设置成员变量?



>我正在尝试将成员变量存储在R列表的方法中。

例:

myclient <- list()
myclient$Login <- function(userName, password) {
# contact the server and get a token; in this example, just set a value to the token:
token <- 5
#... then, store the just received token in a member variable
myclient$token <- token
cat(myclient$token)
}
myclient$Login('user', '12345')
cat(myclient$token)

指纹:

5
NULL

即:成员变量(myclient$token(在退出函数(登录(时被销毁。

有没有办法以某种方式存储它,以便:

1(可以重复使用

2(用户(登录函数的调用者(对成员变量(myclient$token(保持不可知

性?

我最终使用双箭头 (<<-( 运算符全局存储成员变量:

myclient <- list()
myclient$Login <- function(userName, password) {
# contact the server and get a token; in this example, just set a value to the token:
token <- 5
#... then, store the just received token in a member variable
# Notice the double arrow, here!
myclient$token <<- token
cat(myclient$token)
}
myclient$Login('user', '12345')
cat(myclient$token)

指纹:

5
5

最新更新