首页 > 解决方案 > 如何有效地重新编码?

问题描述

我有以下课程

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 将被调用一次且仅调用一次。但是,由于我计算了startand endin _function_1,所以我不想在调用_function_2. 如何避免这种情况?

标签: pythonperformance

解决方案


由于我们只需要执行一次函数,但不知道是否function_1先执行function_2,可以使用以下思路:

  1. 如果可能,您可以在方法本身中调用该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
  1. 如果由于某种原因该声明不适用于您的程序,您可以使用简单的检查来检查该函数是否已被调用。
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同时分配startend,计算只会发生一次。


推荐阅读