Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

python - Storing calculated values in an object

Recently I've been writing a bunch of code like this:

class A:
  def __init__(self, x):
    self.x = x
    self._y = None

  def y(self):
    if self._y is None:
      self._y = big_scary_function(self.x)

    return self._y

  def z(self, i):
    return nice_easy_function(self.y(), i)

In a given class I may have a number of things working like this y, and I may have other things that use the stored pre-calculated values. Is this the best way to do things or would you recommend something different?

Note that I don't pre-calculate here because you might use an instance of A without making use of y.

I've written the sample code in Python, but I'd be interested in answers specific to other languages if relevant. Conversely I'd like to hear from Pythonistas about whether they feel this code is Pythonic or not.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As a self-proclaimed Pythonista, I would prefer using the property decorator in this situation:

class A:
    def __init__(self, x):
        self.x = x

    @property
    def y(self):
        if not hasattr(self, '_y'):
            self._y = big_scary_function(self.x)
        return self._y

    def z(self, i):
        return nice_easy_function(self.y, i)

Here self._y is also lazy evaluated. The property allows you to refer to self.x and self.y on the same footing. That is, when working with an instance of the class, you treat both x and y as attributes, even though y is written as a method.

I've also used not hasattr(self, '_y') instead of self._y is None, which allows me to skip the self.y = None declaration in __init__. You can of course use your method here and still go with the property decorator.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...