0

I have a lot of code that uses properties like given below, and I wonder whether there is a better way to store/return the value of the property since all that code seems quite repetitive and also having to specify the self._a and so on in __init__ is not exactly beautiful...

class X:
    def __init__(self):
        self._a = None
        self._b = None

    @property
    def a(self):
        if self._a is None: self._a = expensive_function()
        return self._a

    @property
    def b(self):
        if self._b is None: self._b = another_expensive_function()
        return self._b
zabbarob
  • 1,191
  • 4
  • 16
  • 25

1 Answers1

1

You could avoid setting the hidden arguments to None by using if not hasattr(self, '_a'): self._a = expensive_function().

To get rid of the repetitive stuff you might use some decorator function.

Bas Swinckels
  • 18,095
  • 3
  • 45
  • 62