gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:59:38 25 4
gpt4 key购买 nike

我正在努力寻找一种方法来使用定义为 @classmethod 的备用构造函数来创建类工厂(我使用 factory_boy 版本 2.11.1 和 Python 3)。

假设我们有一个用于构建带有默认构造函数和 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.

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

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

最佳答案

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

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

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

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

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

coords = (1., 2.)

关于python - 工厂调用备用构造函数(类方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50934517/

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