Skip to content

Instantly share code, notes, and snippets.

@onjin
Created April 4, 2014 16:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save onjin/9977712 to your computer and use it in GitHub Desktop.
Save onjin/9977712 to your computer and use it in GitHub Desktop.
lazy property
import math
class lazyproperty(object):
def __init__(self, func):
self.func = func
def __get__(self, instance, cls):
if instance is None:
return self
else:
value = self.func(instance)
setattr(instance, self.func.__name__, value)
return value
class Circle(object):
def __init__(self, radius):
self.radius = radius
@lazyproperty
def area(self):
print("do math")
return math.pi * self.radius ** 2
if __name__ == '__main__':
c = Circle(4.0)
# lazyproperty calls setattr(instance, self.func.__name__, value)
print c.area
# just get previously set property
print c.area
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment