Skip to content

Instantly share code, notes, and snippets.

@minghan
Created July 7, 2011 18:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save minghan/1070187 to your computer and use it in GitHub Desktop.
Save minghan/1070187 to your computer and use it in GitHub Desktop.
Python Memoize Example
# 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