ericmjl
ericmjl

Reputation: 14714

How to make Python object pre-compute a property if the property is currently None?

I am writing a Python object for storing some data. One of the data that I would like to be associated with the object has to be computed in a stochastic fashion (it is a "null model" of sorts). Therefore, I would like the function to do the following:

A very, very simple toy example of what I am trying to accomplish is as follows. Suppose I have an object called Object. It is currently set up as follows:

from random import random

class Object(object):

    def __init__(self):
        self._x = None

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self):
        self._x = random() # Assume that this is the stochastic thing to compute.

What I would like to achieve is this:

>> O = Object()
>> print O.x
<result of computation printed here, rather than "None">

Is this possible to do? If so, how would I achieve this? If not, what would be the best way for me to write the code?

Upvotes: 1

Views: 615

Answers (1)

dano
dano

Reputation: 94951

Just have your getter initialize _x if it's None:

from random import random

class Object(object):

    def __init__(self):
        self._x = None

    @property
    def x(self):
        if self._x is None:
            self._x = random()
        return self._x

Upvotes: 4

Related Questions