【发布时间】:2018-06-19 18:05:13
【问题描述】:
我正在努力寻找一种方法来使用定义为 @classmethod 的替代构造函数来创建类 Factory(我使用 factory_boy 版本 2.11.1 和 Python 3)。
假设我们有一个用于构建 2D 点对象的类,该类具有默认构造函数和 2 个附加构造函数:
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)
我创建了一个基本的点工厂:
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,如果你弄
model = Point.fromlist会怎么样?从语义上讲,它们都是接受参数并返回Point实例的可调用对象——我觉得这可能是一种方法。
标签: python python-3.x testing class-method factory-boy