在驼鹿中,如何为子类中的超级类指定构造函数?

发布于 2025-01-17 11:15:55 字数 119 浏览 2 评论 0原文

我有一个带有一些属性的 Moose 类(xyz)。我对它进行子类化,对于子类,x 始终为 3。我如何在子类中指定它?

I have a Moose class with some properties (x,y,z). I subclass it, and for the subclass, x is always 3. How can I specify this in subclass?

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

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

发布评论

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

评论(2

街道布景 2025-01-24 11:15:55

一个人可以使用 build> buildargs buildargs

around BUILDARGS => sub {
    my $orig  = shift;
    my $class = shift;
 
    return $class->$orig(@_, x => 3 );
};

One could use BUILDARGS.

around BUILDARGS => sub {
    my $orig  = shift;
    my $class = shift;
 
    return $class->$orig(@_, x => 3 );
};
薄暮涼年 2025-01-24 11:15:55

我以前和 Moo 一起工作过,但看起来是一样的。您只需使用 + 在子类中声明属性即可覆盖之前的声明。

package Foo;
use Moose;
 
has 'a' => (
    is => 'rw',
    isa => 'Num',
);

has 'b' => (
    is => 'rw',
    isa => 'Num',
);

has 'c' => (
    is => 'rw',
    isa => 'Num',
);


package My::Foo;
use Moose;
 
extends 'Foo';
 
has '+a' => (
    default => 3,
);

I used to work with Moo but it seems to be the same. You just need to declare the property in the subclass using + to override previous declaration.

package Foo;
use Moose;
 
has 'a' => (
    is => 'rw',
    isa => 'Num',
);

has 'b' => (
    is => 'rw',
    isa => 'Num',
);

has 'c' => (
    is => 'rw',
    isa => 'Num',
);


package My::Foo;
use Moose;
 
extends 'Foo';
 
has '+a' => (
    default => 3,
);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文