gpt4 book ai didi

perl - 为 Moo 只读属性设置编写器名称是否使其可读写?

转载 作者:行者123 更新时间:2023-12-02 08:07:27 24 4
gpt4 key购买 nike

我正在研究 Moo 并遇到了这个基本问题。如果我为只读属性设置访问器或编写器名称,则该属性变为可写。访问器或编写器是否暗示属性是可写的,即使它被设置为只读(is => 'ro')?

这是类代码:

#!/home/fl/perl5/perlbrew/perls/perl-5.26.1/bin/perl
package MooPerson;
use Moo;
use namespace::clean;

has firstname => (
is => 'rw',
reader => 'get_firstname',
writer => 'set_firstname',
);

has surname => (
is => 'ro',
reader => 'get_surname',
writer => 'set_surname',
);

sub get_fullname {
my ($self) = @_;
my $firstname = $self->get_firstname;
my $surname = $self->get_surname;
return "$firstname $surname";
}
1;

目标代码:

#!/home/fl/perl5/perlbrew/perls/perl-5.26.1/bin/perl
use lib 'lib';
use MooPerson;
use feature 'say';
use strict;
use warnings;

say "new object person";
my $person = MooPerson->new(
firstname => 'Homer',
surname => 'Simpson',
);

say "person->get_firstname: " . $person->get_firstname();
say "person->get_surname: " . $person->get_surname();

say "\nchange firstname and surname";
$person->set_firstname('Aristotle');
$person->set_surname('Amadopolis');

say "person->get_firstname: " . $person->get_firstname();
say "person->get_surname: " . $person->get_surname();

结果:

fl@dancertest:~/perltest$ ./firstMoo.pl
new object person
person->get_firstname: Homer
person->get_surname: Simpson

change firstname and surname
person->get_firstname: Aristotle
person->get_surname: Amadopolis

当我使用访问器时会发生同样的行为。(is => 'ro') 仅当我使用自动生成的访问器名称时才有效,在本例中为“姓氏”。

这是预期的行为还是错误?

非常感谢。

最佳答案

是的,因为 is 不会将任何内容设为只读;它只是创建一个访问器。

  • is => 'rw' 只是 accessor => 'attribute_name' 的快捷方式。
  • is => 'ro' 只是 reader => 'attribute_name' 的快捷方式。

如果您指定了一个writer,您将能够写入该属性,即使您使用了is => 'ro'

如果我想要一个公共(public)读者和一个私有(private)/ protected 作者,我使用

has surname => (
reader => 'get_surname',
writer => '_set_surname',
);

has surname => (
reader => 'surname',
writer => '_set_surname',
);

关于perl - 为 Moo 只读属性设置编写器名称是否使其可读写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50187573/

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