, . .
. property ( ). - , __get__. , , , - (, ). .
class cache:
def __init__(self, func):
self.func = func
def __get__(self, obj, type_):
if obj is None:
return self.func
value = self.func(obj)
setattr(obj, self.func.__name__, value)
return value
class MyClass:
def __init__(self, x, y):
self.x = x
self.y = y
@cache
def calculate(self):
print("calculating")
return self.x + self.y
o = MyClass(1, 2)
print("first", o.calculate)
print("second", o.calculate)
del o.calculate
print("third", o.calculate)