Python __call__ special method practical example

后端 未结 14 1618
感动是毒
感动是毒 2020-11-28 00:28

I know that __call__ method in a class is triggered when the instance of a class is called. However, I have no idea when I can use this special method, because

14条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-28 00:57

    This example uses memoization, basically storing values in a table (dictionary in this case) so you can look them up later instead of recalculating them.

    Here we use a simple class with a __call__ method to calculate factorials (through a callable object) instead of a factorial function that contains a static variable (as that's not possible in Python).

    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()
    

    Now you have a fact object which is callable, just like every other function. For example

    for i in xrange(10):                                                             
        print("{}! = {}".format(i, fact(i)))
    
    # output
    0! = 1
    1! = 1
    2! = 2
    3! = 6
    4! = 24
    5! = 120
    6! = 720
    7! = 5040
    8! = 40320
    9! = 362880
    

    And it is also stateful.

提交回复
热议问题