处理功能和子功能的最佳方法

时间:2019-01-31 10:42:25

标签: python

在按特定顺序使用它们的情况下,处理函数和使用子函数的“ Pythonic”方式是什么?

由于其中一种想法似乎是函数应该做1件事,因此我遇到一种情况,我发现自己在函数具有固定执行顺序的情况下拆分了函数。 当功能确实是一种“执行步骤1”,“然后获得步骤1的结果,执行步骤2”时,我目前最终将步骤功能包装到另一个功能中,同时在同一级别上对其进行定义。但是,我想知道这是否确实是我应该这样做的方式。

示例代码:

def step_1(data):
    # do stuff on data
    return a

def step_2(data, a):
    # do stuff on data with a
    return b

def part_1(data):
    a = step_1(data)
    b = step_2(data, a)

    return a, b

def part_2(data_set_2, a, b):
    # do stuff on data_set_2 with a and b as input

    return c

我将从另一个文件/脚本(或Jupyter笔记本)中以part_1的形式调用此名称,然后以part_2的形式调用 似乎对于我的目的而言现在工作还不错,但是正如我说的那样,我想知道在这个(早期)阶段是否应该使用其他方法。

2 个答案:

答案 0 :(得分:0)

我想您可以在这里使用Class,否则可以使用以下代码使代码更短:

def step_1(data):
    # do stuff on data
    return step_2(data, a)

def step_2(data, a):
    # do stuff on data with a
    return a, b

def part_2(data_set_2, a, b):
    # do stuff on data_set_2 with a and b as input

    return c

答案 1 :(得分:0)

As a rule of thumb, if more functions use the same arguments, it is a good idea to group them together into a class. But you can also define a main() or run() function that makes uses of your functions in a sequential fashion. Since the example you have made is not too complex, I would avoid using classes and go for something like:

def step_1(data):
    # do stuff on data
    return step_2(data, a)

def step_2(data, a):
    # do stuff on data with a
    return a, b

def part_2(data_set_2, a, b):
    # do stuff on data_set_2 with a and b as input
    return c


def run(data, data_set_2, a, b):
    step_1(data)
    step_2(data, a)
    part_2(data_set_2, a, b)

run(data, data_set_2, a, b)

If the code grows in complexity, using classes is advised. In the end, it's your choice.