Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...