1

decorator @property与python中的任何等价物吗?

也就是说,由于另一个字段的更新,一个字段会自动更新(访问时),而不是在访问之前重新计算它。

更新 2014-02-06

通过将“一个”字段定义activeBindingFunction为“另一个”字段的一个,可以打开自动更新(参见@jdharrison 的答案)。但是,有没有办法检查这样的更新是否是惰性评估?如果没有,我们怎样才能做到这一点?

(后来的编辑:内部的“非正式”打印功能activeBindingFunction很明显评估是惰性的。有什么方法可以更正式地检查这个问题吗?)

为了更好地说明我的问题,下面是一段 python 代码,它通过decorator @property- 产生所需的惰性行为 - 请耐心等待我将其放入带有R标记的问题中。

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)

互动环节

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}
4

1 回答 1

1

不确定它是否是你所追求的

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 
于 2014-02-06T09:00:48.597 回答