vendredi 16 septembre 2016

Difference between attribute and property

I'm using lazy initialization in Python in order to save loading time. I've some properties that are initialized only when they are used, so if they are never used, the cost for creating them are never charged. An example of it is this:

class myClass(object):
    anotherInfo = 1
    def __init__(self,var):
        self._MY_DATA = None
        self.var = var

    @property
    def my_data(self):
        if getattr(self, '_MY_DATA', None) is None:
            print "Populate my_data"
            my_data = self.var
            self._MY_DATA = my_data
        return self._MY_DATA

    def invalidate_data(self):
        self._MY_DATA = None

if __name__ == '__main__':
    x = myClass("1")
    print x.my_data
    x.invalidate_data()
    print x.my_data

My problem is the following, some events cause all properties to loose state, and I've to reset all of them (to the never used state). I want to do this automatically, so I need a list of all properties.

I could get this through reflection using the inspect mode, but I did not found any way of doing so.

Another is to add the property each time I execute the @property wrapper, but how can a write a wrapper that receives the getter function and the object in order to save the properties ?

The other method is to wrap the @property wrapper, in order to append to a list in the object(e.g. __properties__) what are my properties to reset.





Aucun commentaire:

Enregistrer un commentaire