python - 如何有效地重新编码?
问题描述
我有以下课程
class Problem:
def __init__(self, instance: Instance):
self.instance = instance
self.solution = Solution.empty_solution()
def _compute_start_end(self):
....
return start, end
def _fuction_1(self):
start, end = self._compute_start_end()
....
def _function_2(self):
start, end = self._compute_start_end()
....
对于这种类型的每个对象,函数 1 和 2 将被调用一次且仅调用一次。但是,由于我计算了start
and end
in _function_1
,所以我不想在调用_function_2
. 如何避免这种情况?
解决方案
由于我们只需要执行一次函数,但不知道是否function_1
先执行function_2
,可以使用以下思路:
- 如果可能,您可以在方法本身中调用该
compute
函数。init
def __init__(self, params):
....
self._compute_start_end()
def _compute_start_end(self):
....
self.start, self.end = start, end
def function_1(self):
#use self.start and self.end
def function_2(self):
#use self.start and self.end instead of recomputing
- 如果由于某种原因该声明不适用于您的程序,您可以使用简单的检查来检查该函数是否已被调用。
def __init__(self, params):
....
self.start, self.end = None, None
def _compute_start_end(self):
if (self.start or self.end):
return
....
self.start, self.end = start, end
def function_1(self):
self._compute_start_end()
#use self.start and self.end
def function_2(self):
self._compute_start_end()
#use self.start and self.end instead of recomputing
只要您不None
同时分配start
和end
,计算只会发生一次。
推荐阅读
- javascript - javascript 对象被定义然后它是未定义的。对象和函数共享同一个对象
- javascript - 使用公共 api 将数据提取到我的 html 页面中。需要帮助找出要提取的对象的名称
- linux - 在这些 tar 和 gzip 命令中,独立的“-”有什么作用?
- xfs - 我如何知道是否完成了现金加载/现金补充操作
- .net - 从我的 .NET 应用程序的安装程序中诊断丢失的 DLL/程序集的更好方法是什么?
- ios - 试图将 Compositional Layout CollectionView 与 PageControl 连接起来。visibleItemsInvalidationHandler 没有调用
- json - 从 HTML 模板中删除 \ 字符
- parallel-processing - 是否所有线程在 CUDA 中使用相同数量的寄存器?
- java - 循环如何与堆栈一起工作?它是否将 * 更改为 0 和 1?
- html - 将背景作为主体背景子集的 Div