1

有没有办法从子类调用父工厂的方法?

通常的super(ThisClass, self)orParentClass.method(self)方法不起作用,因为self它不是类的实例,而是工厂返回的对象。

class SomethingFactory(factory.DjangoModelFactory):
    # Meta, fields, etc

    @factory.post_generation
    def post(self, create, extracted, **kwargs):
        # Some steps


class SomethingElseFactory(SomethingFactory):

    @factory.post_generation
    def post(self, create, extracted, **kwargs):
        super(SomethingElseFactory, self).post(create, extracted, **kwargs)

错误是TypeError: super(type, obj): obj must be an instance or subtype of type

(快捷方式super().post(create, extracted, kwargs)会产生相同的错误。)

如何SomethingFactory.post从子类访问该父工厂方法?

4

1 回答 1

1

根据您在基类中尝试执行的操作,post()您可以将其拉出到一个函数中并从两个地方调用它:

def set_attributes(obj):
    obj.attr1 = True
    obj.attr2 = 1000


class SomethingFactory(factory.DjangoModelFactory):
    # Meta, fields, etc

    @factory.post_generation
    def post(self, create, extracted, **kwargs):
        set_attributes(self)


class SomethingElseFactory(SomethingFactory):

    @factory.post_generation
    def post(self, create, extracted, **kwargs):
        set_attributes(self)
        # Do some other stuff
于 2015-11-09T04:27:14.397 回答