Python Language Using the @property decorator


The @property decorator can be used to define methods in a class which act like attributes. One example where this can be useful is when exposing information which may require an initial (expensive) lookup and simple retrieval thereafter.

Given some module

class Foo(object):
    def __init__(self):
        self.__bar = None

    def bar(self):
        if self.__bar is None:
            self.__bar = some_expensive_lookup_operation()
        return self.__bar


>>> from foobar import Foo
>>> foo = Foo()
>>> print(  # This will take some time since bar is None after initialization
>>> print(  # This is much faster since bar has a value now