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

Mar*_*ark 2 python function call

我有一个核心函数,我从我的脚本中的许多其他函数调用.问题是当我调用核心函数来运行它时我不想要每个函数.有没有办法存储核心功能的输出,以便当它被调用第二次,第三次等时它不运行?

例如

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
Run Code Online (Sandbox Code Playgroud)

等等..

在func2调用它之后,func3会再次调用core_func.我怎样才能防止这种情况但同时使用core_func输出?一个可能的解决方案可能是从func2返回输出并在func3中使用(但这会有点难看).

谢谢

cal*_*97g 6

variable = core_func(arguments)

func2(variable)

func3(variable)
Run Code Online (Sandbox Code Playgroud)

将函数的结果存储在变量中!


dan*_*nca 5

你可以使用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
Run Code Online (Sandbox Code Playgroud)

如果您正在使用Python3,那么您可以使用lru_cache装饰器免费使用它

Decorator用一个memoizing callable来包装一个函数,它可以节省maxsize最近的调用.当使用相同的参数定期调用昂贵的或I/O绑定函数时,它可以节省时间.

from functools import lru_cache

@lru_cache(maxsize=32)
def core_func(a, b, c):
  do something....
  return x,y,z
Run Code Online (Sandbox Code Playgroud)