python: are property fields being cached automatically?

后端 未结 8 710
离开以前
离开以前 2020-12-14 15:20

My question is are the following two pieces of code run the same by the interpreter:

class A(object):
  def __init__(self):
     self.__x = None

  @property         


        
相关标签:
8条回答
  • 2020-12-14 16:05

    The decorator from Denis Otkidach mentioned in @unutbu's answer was published in O'Reilly's Python Cookbook. Unfortunately O'Reilly doesn't specify any license for code examples – just as informal permission to reuse the code.

    If you need a cached property decorator with a liberal license, you can use Ken Seehof's @cached_property from ActiveState code recipes. It's explicitly published under the MIT license.

    def cached_property(f):
        """returns a cached property that is calculated by function f"""
        def get(self):
            try:
                return self._property_cache[f]
            except AttributeError:
                self._property_cache = {}
                x = self._property_cache[f] = f(self)
                return x
            except KeyError:
                x = self._property_cache[f] = f(self)
                return x
    
        return property(get)
    
    0 讨论(0)
  • 2020-12-14 16:17

    No, the getter will be called every time you access the property.

    0 讨论(0)
提交回复
热议问题