Created
January 16, 2014 08:29
-
-
Save zelark/8451557 to your computer and use it in GitHub Desktop.
Python __call__ special method practical example
http://stackoverflow.com/questions/5824881/python-call-special-method-practical-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
class Factorial: | |
def __init__(self): | |
self.cache = {} | |
def __call__(self, n): | |
if n not in self.cache: | |
if n == 0: | |
self.cache[n] = 1 | |
else: | |
self.cache[n] = n * self.__call__(n - 1) | |
return self.cache[n] | |
fact = Factorial() | |
for i in xrange(10): | |
print '%d! = %d' % (i, fact(i)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment