gpt4 book ai didi

python - 如何在 Python 类中重用返回值而不用每次都重新运行该函数?

转载 作者:太空宇宙 更新时间:2023-11-04 11:17:25 24 4
gpt4 key购买 nike

我在类中重用函数时遇到问题。我想获取一个函数的返回值,而不是每次使用它时都重新运行它。在类里面执行此操作的最佳方法是什么?

谢谢!

class Test():

def __init__ (self):
# self.my_list = my_list()

pass


@staticmethod
def my_list():
set_list = [1, 2, 3, 4, 5, 6]
print ('you are not refrencing')

return set_list

@staticmethod
def func_test():
func_list = Test.my_list()
return func_list


@staticmethod
def func_test2():
func_list = Test.my_list()
return func_list

@staticmethod
def print_func():
print Test.my_list()
print Test.func_test()
print Test.func_test2()

return

Test.print_func()

这是我目前的结果:

you are not referencing 
[1, 2, 3, 4, 5, 6]
you are not referencing
[1, 2, 3, 4, 5, 6]
you are not referencing
[1, 2, 3, 4, 5, 6]

我会得到这个结果

you are not referencing 
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]

最佳答案

如果你的函数是(没有副作用/相同的输入总是产生相同的输出),你可以使用 @functools.lru_cache 的内存。 ,它缓存给定输入集的输出。 (这是由字典支持的,因此参数必须是可哈希的。)

如果函数不是纯函数(就像你的示例中有 print() 调用),那么添加这个装饰器将改变行为:副作用将在以下调用中被跳过。当您返回一个可变值(如列表)时也要非常小心,因为将返回相同的缓存对象,即使它发生了任何变化,这可能不是您所期望的。

关于python - 如何在 Python 类中重用返回值而不用每次都重新运行该函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56720529/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com