Moose只读属性特征以及如何设置它们?
如何设置 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以在构造函数中设置它:
您只需将其传递给正确的构造函数(属性的构造函数)。
You can set it in the constructor:
You just need to pass it to the right constructor (the constructor for the attribute).
我使用
default
来处理ro
属性:并且由于您不会在其他任何地方设置
myattr
的值,因此使用默认值。I use
default
to deal withro
attributes:And since you won't be setting
myattr
's value anywhere else, the default is used.