我有一个实用程序模块,用于向其他脚本提供数据。我不知道如何在尽量减少函数调用量的同时最好地利用它(为了论证,这些调用都很慢)。你知道吗
它看起来像这样:
helper.py
dataset1 = slow_process1()
dataset2 = slow_process2()
def get_specific_data1():
data = #do stuff with dataset1
return data
def get_specific_data2():
data = #do stuff with dataset1
return data
def get_specific_data3():
data = #do stuff with dataset2
return data
现在,假设我需要在脚本中运行get_specific_data1
。在上面的设置中,我正在导入模块,这意味着在导入时调用slow_process2
是不必要的。你知道吗
如果我嵌套了dataset1
和dataset2
的赋值,但是需要在同一个脚本中调用get_specific_data1
和get_specific_data2
,那么我会运行slow_process1
两次,这也是不必要的。你知道吗
如果我用get_specific_data
函数的方法创建一个Helper
类,如果需要,它运行slow_process1
或slow_process2
,存储数据,然后在调用方法时可以根据需要进行访问,我可以绕过这个问题。这样合适吗?你知道吗
比如:
class Helper:
def __init__(self):
self.dataset1 = None
self.dataset2 = None
def run_dataset1():
self.dataset1 = slow_process1()
def run_dataset2():
self.dataset2 = slow_process2()
def get_specific_data1():
if dataset1 is None:
self.rundataset1()
data = #do stuff with dataset1
return data
etc
抱歉,如果这是一个愚蠢的问题,但我有有限的经验,面向对象,不想犯错误的前面。你知道吗
谢谢
这就是我使用带有properties的类的意思,只是在本例中,我使用了名为
lazyproperty
的类的自定义版本。它被认为是“懒惰”的,因为它只有在被访问时才被计算,就像一个普通的property
,但与它们不同的是,计算出的值被有效地缓存在一种方式中,将其更改为一个实例属性,这样它就不会每次都被重新计算。你知道吗警告:这样做假设值无论何时计算都是相同的,并且在第一次访问之后对它所做的任何更改都将对使用它的类的同一实例的其他方法可见,即它们不会看到新重新计算的值。你知道吗
一旦这样做了,类中的方法就可以引用
self.dataset1
或self.dataset2
,就好像它们是常规的实例属性一样,然后,如果是第一次,将计算与其关联的数据,否则只返回先前创建的值。您可以在生成的输出中看到这种情况(如下所示)。你知道吗输出:
您可以使用延迟加载技术来解决此问题:
这里的副作用是,如果你从来没有时间去检查
dataset1
或dataset2
,它们永远不会加载。你知道吗相关问题 更多 >
编程相关推荐