Created
April 4, 2014 16:02
-
-
Save onjin/9977712 to your computer and use it in GitHub Desktop.
lazy property
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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