python在其他函数中使用一个函数的输出而不调用所有其他函数

问题描述:

我有一个核心函数,我从脚本中的许多其他函数调用。问题是我不希望每个函数调用核心函数来运行它。有没有一种方法来存储核心函数的输出,以便在第二次,第三次调用它时不会运行?python在其他函数中使用一个函数的输出而不调用所有其他函数

E.g. FUNC2呼吁后,在这里

def core_func(a,b,c): 
    do something.... 
    return x,y,z 

def func2(a,b,c): 
    x,y,z = core_func(a,b,c) 
    do something with x,y,z 

def func3(a,b,c): 
    x,y,z = core_func(a,b,c) 
    do something with x,y,z 

等。

FUNC3会再打电话core_func。我怎样才能防止这一点,但同时使用core_func输出?一个可能的解决方案可能会返回来自func2的输出并在func3中使用(但这会变得有点难看)。

感谢

variable = core_func(arguments) 

func2(variable) 

func3(variable) 

保存函数的变量的结果!

您可以使用memoize

每次调用时缓存函数的返回值。

所以,每次你调用函数具有相同的参数时,你会得到的返回值,而不计算时间

即:

如果您使用Python2需要实现它,你可以看看它是如何上面的链接来实现,然后将其应用到你的函数:

class memoized(object): 
     '''Decorator. Caches a function's return value each time it is called. 
     If called later with the same arguments, the cached value is returned 
     (not reevaluated). 
     ''' 
     def __init__(self, func): 
     self.func = func 
     self.cache = {} 
     def __call__(self, *args): 
     if not isinstance(args, collections.Hashable): 
      # uncacheable. a list, for instance. 
      # better to not cache than blow up. 
      return self.func(*args) 
     if args in self.cache: 
      return self.cache[args] 
     else: 
      value = self.func(*args) 
      self.cache[args] = value 
      return value 
     def __repr__(self): 
     '''Return the function's docstring.''' 
     return self.func.__doc__ 
     def __get__(self, obj, objtype): 
     '''Support instance methods.''' 
     return functools.partial(self.__call__, obj) 

@memoized 
def core_func(a, b, c): 
    do something.... 
    return x,y,z 

如果您使用Python3你就把它免费与lru_cache decorator

修饰器用一个可调用的可调用函数包装一个函数,该函数可以将 保存为maxsize最近的调用。当使用相同的参数周期性地调用昂贵的 或I/O绑定函数时,它可以节省时间。

from functools import lru_cache 

@lru_cache(maxsize=32) 
def core_func(a, b, c): 
    do something.... 
    return x,y,z 
+1

这个答案会更好,如果你表现出一个实际的例子 –

+0

@BryanOakley做,只是增加了实例和一个更好的解释。感谢您的反馈。 – danielfranca

+0

永远不知道你可以做到这一点。如果你的函数有很大的开销,那很酷。 – cal97g