我一直在尋找在Python一些延遲加載屬性的裝飾和整個這個例子(http://code.activestate.com/recipes/363602-lazy-property-evaluation/)發生了:這個Python裝飾器是如何工作的?
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
我的問題是,如何工作的呢?我對裝飾器的理解是它們必須是可調用的(因此可以是實現__call__
的函數或調用),但Lazy
顯然不是,如果我嘗試Lazy(someFunc)()
,它會引發異常,如預期的那樣。我錯過了什麼?