我在Python中查看了一些延迟加载属性装饰器,并且发生在这个例子中(http://code.activestate.com/recipes/363602-lazy-property-evaluation/):
class Lazy(object):
def __init__(self, calculate_function):
self._calculate = calculate_function
def __get__(self, obj, _=None):
if obj is None:
return self
value = self._calculate(obj)
setattr(obj, self._calculate.func_name, value)
return value
# Sample use:
class SomeClass(object):
@Lazy
def someprop(self):
print 'Actually calculating value'
return 13
o = SomeClass()
o.someprop
o.someprop
Run Code Online (Sandbox Code Playgroud)
我的问题是,这是如何工作的?我对装饰器的理解是它们必须是可调用的(所以要么是函数,要么是实现的调用__call__),但是Lazy这里显然不是,如果我尝试Lazy(someFunc)()它会引发异常,如预期的那样.我错过了什么?