Auto update of a field (data member) in R reference class

大城市里の小女人 提交于 2020-01-14 03:30:06

问题


Any equivalent as the decorator @property in python?

That is to have one field automatically updated (on access) due to an update of another field, instead of recomputing it before access.

UPDATE 2014-02-06

By defining "one" field as an activeBindingFunction of "another" field turns on the automatic updates (See @jdharrison's answer). However, is there anyway to check whether such updates are lazy evaluation? If not, how can we achieve this?

(A later edit: an "informal" print function inside the activeBindingFunction is evident that the evaluation is lazy. Any way to check this issue in a more formal manner?)

For better illustration of my question, below is a piece of python code producing the desired lazy behavior via decorator @property - bear with me to put it in an R-tagged question.

class Test(object):
    def __init__(self):
        self._num1=None
        self._num2=None

    @property
    def num1(self):
        if (self._num1 is None):
            self._num1=1
            return(self.num1)
        else:
            return(self._num1)

    @num1.setter
    def num1(self, value):
        self._num1 = value

    @property
    def num2(self):
        self._num2=self._num1*2
        return(self._num2)

The interactive session

In [2]: obj=Test()

In [3]: obj.__dict__
Out[3]: {'_num1': None, '_num2': None}

In [4]: obj.num1
Out[4]: 1

In [5]: obj.__dict__
Out[5]: {'_num1': 1, '_num2': None}

In [6]: obj.num2
Out[6]: 2

In [7]: obj.__dict__
Out[7]: {'_num1': 1, '_num2': 2}

In [8]: obj.num1 = 5

In [9]: obj.__dict__
Out[9]: {'_num1': 5, '_num2': 2}

In [10]: obj.num2
Out[10]: 10

In [11]: obj.__dict__
Out[11]: {'_num1': 5, '_num2': 10}

回答1:


Not sure if its what you are after

test <- setRefClass("test",
                            fields   = list(
                                            num1 = "numeric"
                                            , num2 = function(){
                                                                print("hello")
                                                                 2*.self$num1
                                                                }
                                           ),
                            methods  = list(
                              initialize = function(num1 = 1){
                                num1 <<- num1
                              },

                              show = function(){
                                print(c(num1 = num1, num2 = num2))
                              }
                            )
)

> tt <- test()
> tt
[1] "hello;"
num1 num2 
   1    2 
> tt$num1<-4
> tt
[1] "hello;"
num1 num2 
   4    8 


来源:https://stackoverflow.com/questions/21587410/auto-update-of-a-field-data-member-in-r-reference-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!