使用属性装饰器
@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