我如何需要一个不是属性的 Moose 构造函数参数?
我有一个 Moose 对象模块,它应该接受相对较大的数据结构 (ds
) 作为其构造函数参数之一。它用于计算对象的一些属性。但是,我不希望将 ds 本身存储为属性——只有在对象构造过程中才需要它。
我想过使用 BUILDARGS
但后来我不确定如何定义 ds
是必需的参数。
我该如何解决这个问题?
I have a Moose object module that should accept a relatively large data structure (ds
) as one of its constructor arguments. It is used to calculate some of the object's attributes. However, I do not wish to store ds
itself as an attributes -- it is only needed during the construction of the object.
I thought of using BUILDARGS
but then I'm not sure how to define that ds
is a required argument.
How can I work around this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我倾向于有一个构造函数,它只采用从数据结构派生的计算值。然后使用不同的方法将有限的参数加上数据结构作为参数。
然后让你的对象像这样:
现在你不必担心奇怪的序列化问题或 BUILDARGS 甚至 BUILD。你有一个简单的方法,仅此而已。
I'd be inclined to have a constructor that takes only the calculated values derived from your data structure. Then use a different method to take limited params plus the data structure as args.
Then make your objects like so:
Now you don't have to worry about weird serialization issues or BUILDARGS or even BUILD. You have a simple method and that is all.
您可以使用
BUILD
或BUILDARGS
来实现此目的。如果不了解更多关于您想要做什么的信息,很难说哪个更好,但我猜BUILD
会是更好的选择。如果您希望 Moose 检查类型并确保它存在,则必须将其设为属性。但你可以在使用后在
BUILD
方法中清除它。如果您愿意,您可以将 reader 方法命名为其他名称(例如
_ds
)。You could use either
BUILD
orBUILDARGS
for this. It's hard to say which would be better without knowing more about what you're trying to do, but I'd guessBUILD
would be the better choice.If you want Moose to check the type and ensure it's present, you have to make it an attribute. But you can clear it in the
BUILD
method after you use it.You could name the reader method something else (like
_ds
) if you wanted to.