Find Out If a Function has been Called

前端 未结 5 1399
遇见更好的自我
遇见更好的自我 2020-12-05 08:18

I am programming in Python, and I am wondering if i can test if a function has been called in my code

def example():
    pass
example()
#Pseudocode:
if exam         


        
5条回答
  •  天涯浪人
    2020-12-05 08:46

    Memoization functions have been around since the 1960s. In python you can use them as decorators on your example() function.

    The standard memoization function looks something like this:

    def memoize(func):
        memo = {}
        def wrapper(*args):
            if not args in memo:
                memo[args] = func(*args)
            return memo[args]
        return wrapper 
    

    and you decorate your function like this:

    @memoize
    def example():
        pass
    

    In python3.2, you can use the functools.lru_cache instead of the memoziation function.

    import functools
    
    @functools.lru_cache(maxsize=None)
    def example():
         pass
    

提交回复
热议问题