简体   繁体   中英

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

Is there a way to call a parent factory's method from a subclass?

The usual super(ThisClass, self) or ParentClass.method(self) methods don't work, because self isn't an instance of the class, it is the object that the factory returns.

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)

The error is TypeError: super(type, obj): obj must be an instance or subtype of type .

(The shortcut super().post(create, extracted, kwargs) generates the same error.)

How can I access that parent factory SomethingFactory.post method from the sub-class?

Depending on what you are trying to do in the base class post() can you pull it out into a function and call it from both places:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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