如何从类方法访问 Moose 属性?
考虑以下代码:
package Test1;
use Moose;
has 'something' => (
is => 'rw',
default => 'BLAH!'
);
sub printSomething {
my ($self) = @_;
## What should I use here to get the value of something?
print $self->something;
}
package Test2;
Test1->printSomething();
printSomething
如何访问something
?
Consider the following code:
package Test1;
use Moose;
has 'something' => (
is => 'rw',
default => 'BLAH!'
);
sub printSomething {
my ($self) = @_;
## What should I use here to get the value of something?
print $self->something;
}
package Test2;
Test1->printSomething();
How can printSomething
access something
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不可以。您必须实例化一个
Test1
对象才能构造属性默认值。他们不在课堂上闲逛。如果你想在 Moose 中获得真正的类属性,你可以编写一个方法来关闭某些内容并返回它:
当然,如果你需要的话,你还必须做更多的工作来添加设置器和清除器等等。更好的方法是像这样使用 MooseX::ClassAttribute :
这样做的好处是让 Moose 意识到你的类属性,并自动添加元内省的优点。
It can't. You have to instantiate a
Test1
object in order for attribute defaults to be constructed. They don't hang out in the class.If you want true class attributes in Moose, you can just write a method that closes over something and returns it:
Of course, then you have to do some more work to add setters and clearers and whatnot, if you need those. A better way is to use MooseX::ClassAttribute like this:
That has the advantage of making Moose aware of your class attribute, and adding in meta-introspection goodness automatically.