有没有办法从子类调用父工厂的方法?
通常的chars = 'abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ'
ps = [p for p in itertools.permutations(chars, 3)]
random.shuffle(ps)
或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)
方法?
答案 0 :(得分: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