Created
July 7, 2011 18:28
-
-
Save minghan/1070187 to your computer and use it in GitHub Desktop.
Python Memoize Example
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
# Memoize Example | |
class Pak(object): | |
# Do not use @staticmethod here | |
def memoize(key): | |
def decfunc(f): | |
def newfunc(self): | |
if not hasattr(self, key): | |
setattr(self, key, f(self)) | |
else: | |
print "retrieve from mem" | |
return getattr(self, key) | |
return newfunc | |
return decfunc | |
@memoize('c') | |
def getc(self): | |
print "computing" | |
return 1 + 1 | |
p = Pak() | |
p.getc() | |
p.getc() | |
p.getc() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment