Moose只读属性特征以及如何设置它们?

发布于 2024-09-06 10:07:32 字数 712 浏览 4 评论 0原文

如何设置 Moose 只读属性特征?

package AttrTrait;
use Moose::Role;
has 'ext' => ( isa => 'Str', is => 'ro' );

package Class;
has 'foo' => ( isa => 'Str', is => 'ro', traits => [qw/AttrTrait/] );

package main;
my $c = Class->new( foo => 'ok' );
$c->meta->get_attribute('foo')->ext('die') # ro attr trait

如果无法在构造函数或运行时设置只读属性特征,那么它的用途是什么? Moose::Meta:: 中缺少什么吗?属性?有没有办法使用meta来设置它?

$c->meta->get_attr('ext')->set_value('foo') # doesn't work either (attribute trait provided not class provided method)

How do I set a Moose read only attribute trait?

package AttrTrait;
use Moose::Role;
has 'ext' => ( isa => 'Str', is => 'ro' );

package Class;
has 'foo' => ( isa => 'Str', is => 'ro', traits => [qw/AttrTrait/] );

package main;
my $c = Class->new( foo => 'ok' );
$c->meta->get_attribute('foo')->ext('die') # ro attr trait

What is the purpose of Read Only attribute traits if you can't set it in the constructor or in runtime? Is there something I'm missing in Moose::Meta::Attribute? Is there a way to set it using meta?

$c->meta->get_attr('ext')->set_value('foo') # doesn't work either (attribute trait provided not class provided method)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

逐鹿 2024-09-13 10:07:32

您可以在构造函数中设置它:

package Class;
has 'foo' => ( isa => 'Str', is => 'ro', ext => 'whatever', traits => ['AttrTrait'] );

您只需将其传递给正确的构造函数(属性的构造函数)。

You can set it in the constructor:

package Class;
has 'foo' => ( isa => 'Str', is => 'ro', ext => 'whatever', traits => ['AttrTrait'] );

You just need to pass it to the right constructor (the constructor for the attribute).

九歌凝 2024-09-13 10:07:32

我使用 default 来处理 ro 属性:

package Foo;
use Moose;
has 'myattr' => (is => 'ro', default => 'my value goes here');

并且由于您不会在其他任何地方设置 myattr 的值,因此使用默认值。

I use default to deal with ro attributes:

package Foo;
use Moose;
has 'myattr' => (is => 'ro', default => 'my value goes here');

And since you won't be setting myattr's value anywhere else, the default is used.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文