首页 > 解决方案 > 如何减少函数中的重复,主要区别在于被调用子函数的名称

问题描述

代码是这样的:

def func1(p1,p2,p3):
   #do samething
   res = func_a(p1,p3)  # a
   res = func_a(p2,p3)
   return res

def func2(p1,p2,p3):
   #do samething
   res = func_b(p1,p3)  # b
   res = func_b(p2,p3)
   return res

def func3(p1,p2,p3):
   #do samething
   res = func_c(p1,p3)  # c
   res = func_c(p2,p3)
   return res

我不确定向函数添加额外的参数是个好主意,因为我已经有 3 个参数。

但是没有进一步优化,目前的代码在部分重复太多了#do samething。(如下面的原始代码)。

我怎样才能改进它?


    @staticmethod
    def align_bev_tuple(relative_poses_tuple, t_index, *bev):
        if t_index == 0: 
            return bev
        ego_motion_matrix, dataAug_compensate_matrix = relative_poses_tuple
        if dataAug_compensate_matrix is not None:
            bev = list_2d_affine(
                bev, dataAug_compensate_matrix[:, t_index, :, :])
        output = list_2d_affine(
            bev, ego_motion_matrix[:, t_index, :, :])
        return output

    @staticmethod
    def align_bev_single_state(relative_poses_tuple, t_index, hidden_state):
        if t_index == 0:
            return hidden_state
        ego_motion_matrix, dataAug_compensate_matrix = relative_poses_tuple
        if dataAug_compensate_matrix is not None:
            hidden_state = bev_affine(
                hidden_state, dataAug_compensate_matrix[:, t_index, :, :])
        output = bev_affine(
            hidden_state, ego_motion_matrix[:, t_index, :, :])
        return output

    @staticmethod
    def align_bev_tensor(relative_poses_tuple, t_index, hidden_state):
        if t_index == 0:
            return hidden_state
        ego_motion_matrix, dataAug_compensate_matrix = relative_poses_tuple
        if dataAug_compensate_matrix is not None:
            hidden_state = tensor_2d_affine(
                hidden_state, dataAug_compensate_matrix[:, t_index, :, :])
        output = tensor_2d_affine(
            hidden_state, ego_motion_matrix[:, t_index, :, :])
        return output

标签: pythonpython-3.xstyleszen-of-python

解决方案


推荐阅读