gpt4 book ai didi

python - 在〜Factory子类中调用factory_boy父类(super class)方法,不带 `self`

转载 作者:太空宇宙 更新时间:2023-11-03 17:19:35 24 4
gpt4 key购买 nike

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

通常的 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 必须是 type 的实例或子类型

(快捷方式 super().post(create, extract, 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

关于python - 在〜Factory子类中调用factory_boy父类(super class)方法,不带 `self`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33306001/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com