在python中执行步骤的最佳设计模式

Rod*_*Ney 2 python oop design-patterns

我必须以依赖顺序的方式顺序执行多个动作.

StepOne(arg1, arg2).execute()
StepTwo(arg1, arg2).execute()
StepThree(arg1, arg2).execute()
StepFour(arg1, arg2).execute()
StepFive(arg1, arg2).execute()
Run Code Online (Sandbox Code Playgroud)

它们都从同一个Step类继承并获得相同的2个args.

class Step:
    def __init__(self, arg1, arg2):
        self.arg1 = arg1
        self.arg2 = arg2

    def execute(self):
        raise NotImplementedError('This is an "abstract" method!')
Run Code Online (Sandbox Code Playgroud)

按顺序执行这些操作的最惯用方法是什么?是否有适用于此处的设计模式?

Kar*_*rin 6

您可以创建步骤类的列表,然后实例化并在循环中调用它们.

step_classes = [StepOne, StepTwo, StepThree, ...]

for c in step_classes:
    c(arg1, arg2).execute()
Run Code Online (Sandbox Code Playgroud)

  • 我可能会做`for step in map(lambda c:c(arg1,arg2),step_classes):step.execute()`,但它确实没关系.我只是喜欢分离关注点. (3认同)
  • @RodrigoNey完全正确.您只是存储类类型列表.它们直到`c(arg1,arg2)`才会被创建. (2认同)