使用屬性裝飾器

@property 裝飾器可用於在類中定義類似屬性的方法。這可能有用的一個例子是當暴露可能需要初始(昂貴)查詢和之後的簡單檢索的資訊時。

鑑於一些模組 foobar.py

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

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

然後

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