python在其他函数中使用一个函数的输出,而不调用所有其他函数
我有一个核心函数,我从脚本中的许多其他函数调用它。问题是我不希望每个函数调用核心函数来运行它。有没有一种方法可以存储核心函数的输出,以便在第二次、第三次调用时不会运行 例如 等等 这里的func3将在func2调用core_func之后再次调用它。如何防止这种情况,但同时使用core_func输出?一个可能的解决方案可能是返回func2的输出并在func3中使用(但这会有点难看) 谢谢 将函数结果存储在变量中 您可以使用 每次调用函数时缓存函数的返回值 因此,每次使用相同的参数调用函数时,都会得到返回值,而不需要计算时间 i、 e: 如果您使用的是Python2,您需要实现它,您可以在上面的链接上查看它是如何实现的,然后将其应用于您的函数:python在其他函数中使用一个函数的输出,而不调用所有其他函数,python,function,call,Python,Function,Call,我有一个核心函数,我从脚本中的许多其他函数调用它。问题是我不希望每个函数调用核心函数来运行它。有没有一种方法可以存储核心函数的输出,以便在第二次、第三次调用时不会运行 例如 等等 这里的func3将在func2调用core_func之后再次调用它。如何防止这种情况,但同时使用core_func输出?一个可能的解决方案可能是返回func2的输出并在func3中使用(但这会有点难看) 谢谢 将函数结果存储在变量中 您可以使用 每次调用函数时缓存函数的返回值 因此,每次使用相同的参数调用函数时,都会得
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,您可以免费使用
Decorator将函数包装为一个可以保存
最新呼叫的最大大小。当价格昂贵时,它可以节省时间
或I/O绑定函数使用相同的参数定期调用
如果你给出一个真实的答案,这个答案会更好example@BryanOakley完成后,只需添加示例和更好的解释。谢谢你的反馈。我不知道你能做到。如果你的函数有很大的开销,那就很酷了。
variable = core_func(arguments)
func2(variable)
func3(variable)
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
from functools import lru_cache
@lru_cache(maxsize=32)
def core_func(a, b, c):
do something....
return x,y,z