Static caching property

Steven D'Aprano steve at pearwood.info
Mon Mar 21 12:36:28 EDT 2016


On Tue, 22 Mar 2016 03:15 am, Ian Kelly wrote:

> On Mon, Mar 21, 2016 at 9:38 AM, Joseph L. Casale
> <jcasale at activenetwerx.com> wrote:
>> With non static properties, you can use a decorator that overwrites the
>> method on the instance with an attribute containing the methods return
>> effectively caching it.
> 
> Can you give an example of what you mean?

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.)


>> What technique for a static property can be used to accomplish what the
>> descriptor protocol does?
>>
>> I need to cache the results of a method on a class across all instances.
> 
> Why not do the same thing but using a class attribute instead of an
> instance attribute?

Properties don't work when called from a class:

py> class Test(object):
...     @property
...     def x(self):
...             return 999
...
py> Test.x == 999
False
py> Test.x
<property object at 0xb7a148b4>



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



-- 
Steven




More information about the Python-list mailing list