gpt4 book ai didi

perl - 如何在 Moose 中定义默认属性属性值?

转载 作者:行者123 更新时间:2023-12-04 06:39:24 24 4
gpt4 key购买 nike

正如标题所暗示的,我希望能够在我的类里面做这样的事情:

use MooseX::Declare;

class MyClass {
default_attribute_propeties(
is => 'ro',
lazy => 1,
required => 1,
);

has [qw( some standard props )] => ();

has 'override_default_props' => (
is => 'rw',
required => 0,
...
);

...
}

也就是说,定义一些默认属性值,这些值将应用于所有属性定义,除非被覆盖。

最佳答案

听起来您想编写一些自定义属性声明,以提供一些默认选项。这在 Moose::Cookbook::Extending::Recipe1 中有介绍,例如:

package MyApp::Mooseish;

use Moose ();
use Moose::Exporter;

Moose::Exporter->setup_import_methods(
install => [ qw(import unimport init_meta) ],
with_meta => ['has_table'],
also => 'Moose',
);

sub has_table
{
my ($meta, $name, %config) = @_;

$meta->add_attribute(
$name,

# overridable defaults.
is => 'rw',
isa => 'Value', # any defined non-reference; hopefully the caller
# passed their own type, which will override
# this one.
# other options you may wish to supply, or calculate based on
# other arguments passed to this function...

%config,
);
}

然后在你的类里面:
package MyApp::SomeObject;

use MyApp::Moosish;

has_table => (
# any normal 'has' options;
# will override the defaults.
);

# remaining class definition as normal.

关于perl - 如何在 Moose 中定义默认属性属性值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4452403/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com