如何从类方法访问 Moose 属性?

发布于 2024-10-31 18:40:27 字数 387 浏览 4 评论 0原文

考虑以下代码:

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 技术交流群。

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

发布评论

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

评论(1

信愁 2024-11-07 18:40:27

不可以。您必须实例化一个 Test1 对象才能构造属性默认值。他们不在课堂上闲逛。

如果你想在 Moose 中获得真正的类属性,你可以编写一个方法来关闭某些内容并返回它:

{
    my $class_attr = 'BLAH!';
    sub something { 
        return $class_attr;
    }
}

当然,如果你需要的话,你还必须做更多的工作来添加设置器和清除器等等。更好的方法是像这样使用 MooseX::ClassAttribute

package Test1;

use Moose;
use MooseX::ClassAttribute;

class_has 'something' => ( 
    is       => 'rw',
    default  => 'BLAH!'
);

这样做的好处是让 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:

{
    my $class_attr = 'BLAH!';
    sub something { 
        return $class_attr;
    }
}

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:

package Test1;

use Moose;
use MooseX::ClassAttribute;

class_has 'something' => ( 
    is       => 'rw',
    default  => 'BLAH!'
);

That has the advantage of making Moose aware of your class attribute, and adding in meta-introspection goodness automatically.

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