Static caching property

Joseph L. Casale jcasale at activenetwerx.com
Mon Mar 21 12:49:47 EDT 2016


> I think Joseph is using "static" in the Java sense of being associated with
> the class rather than an instance. (In Java, members of classes must be
> known at compile-time.)

Yup, so a single value on the class itself, not instance specific.

> But what you can do is have the property refer to a class attribute:
> 
> 
> py> class Test(object):
> ...     _private = 999
> ...     @property
> ...     def x(self):
> ...             return type(self)._private
> ...     @x.setter
> ...     def x(self, value):
> ...             type(self)._private = value
> ...
> py> a = Test()
> py> b = Test()
> py> c = Test()
> py> a.x
> 999
> py> b.x = 50
> py> c.x
> 50
> py> a.x
> 50

Right, but _private refers to an api call that is expensive and may not even be accessed,
so while I may new up three instances of Test across a, b and c, if none of those end up
accessing var x, it shouldn't get fetched. Without some deferred execution, if the value
of _private is a callable whose return value is what I am interested in, it gets invoked the
moment the class is compiled.

In the non static sense this is trivial to accomplish with the descriptor protocol, I am just not
clear for the static sense.

Thanks Ian and Steven,
jlc



More information about the Python-list mailing list