工厂调用备用构造函数(类方法)

Factory calling alternate constructor (classmethod)

我正在努力寻找一种方法来使用定义为 @classmethod.

假设我们有一个 class 用于使用默认构造函数和 2 个附加构造函数构建 2D 点对象:

class Point:

    def __init__(self, x, y):
        self.x = x
        self.y = y

    @classmethod
    def fromlist(cls, coords):  # alternate constructor from list
        return cls(coords[0], coords[1])

    @classmethod
    def duplicate(cls, obj):  # alternate constructor from another Point
        return cls(obj.x, obj.y)

我创建了一个基本的 Point 工厂:

import factory

class PointFactory(factory.Factory):
    class Meta:
        model = Point
        inline_args = ('x', 'y')

    x = 1.
    y = 2.

默认情况下,似乎调用了class的构造函数__init__,这似乎很合乎逻辑。我找不到一种方法将 inline_args 传递为 coords 以使用备用构造函数 fromlist。有办法吗?

这是我第一次工作和建厂,所以我也可能在网上查找错误的关键字...

factory_boy的重点是方便生成测试实例。您只需调用 PointFactory() 即可完成 ,您拥有其余代码的测试实例。 此用例永远不需要使用任何替代构造函数。工厂将只使用主构造函数。

如果您认为必须定义 factory_boy 工厂来测试额外的构造函数,那么您误解了它们的用途。使用factory_boy 个工厂为其他要测试的代码 创建测试数据。您不会使用它们来测试 Point class(除了生成测试数据以将 传递给 您的构造函数之一)。

请注意,仅当您的构造函数根本不接受关键字参数时才需要 inline_args。您的 Point() class 没有这样的限制; xy 可以用作位置参数和关键字参数。您可以安全地从您的定义中删除 inline_args,无论如何工厂都会工作。

如果您必须使用其他构造函数之一(因为您无法使用主构造函数创建测试数据),只需将特定的构造函数方法作为模型传入即可:

class PointListFactory(factory.Factory):
    class Meta:
        model = Point.fromlist

    coords = (1., 2.)