如何在Python中创建可生成不同类的Factory方法?

时间:2019-03-05 20:01:02

标签: python

当前,我有以下内容:

class ConfirmStepAView(UpdateProcessView):
    form_class = ConfirmationForm

    def validate(self):
        if not self.process.A: 
            raise ValidationError

class ConfirmStepBView(UpdateProcessView):
    form_class = ConfirmationForm

    def validate(self):
        if not self.process.B: 
            raise ValidationError

# Usage: 
flow.View(ConfirmStepAView)
flow.View(ConfirmStepBView)

我该如何编写一种工厂方法来动态生成这些类,以便执行类似的操作?

flow.View(ConfirmStepViewFactory('A'))
flow.View(ConfirmStepViewFactory('B'))
flow.View(ConfirmStepViewFactory('Something'))
flow.View(ConfirmStepViewFactory('Else'))

注意:我必须使用这种格式,因为我正在使用第三方库。

1 个答案:

答案 0 :(得分:1)

这是常见的模式。您可以利用python中的闭包来动态创建并返回您的类。

def make_ConfirmStepView(attribute):
    class ConfirmStepView(UpdateProcessView):
        form_class = ConfirmationForm

        def validate(self):
            if not getattr(self.process, attribute): 
                raise ValidationError

    return ConfirmStepView

flow.View(make_ConfirmStepView('A'))
flow.View(make_ConfirmStepView('B'))
flow.View(make_ConfirmStepView('Something'))
flow.View(make_ConfirmStepView('Else'))