繁体   English   中英

在没有`self`的〜Factory子类中调用factory_boy超类方法。

[英]Call a factory_boy super class method in a ~Factory sub-class without `self`

有没有一种方法可以从子类中调用父工厂的方法?

通常的super(ThisClass, self)ParentClass.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方法?

根据您要在基类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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM