有没有办法从子类调用父工厂的方法?
通常的 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/