【发布时间】:2023-03-20 01:28:01
【问题描述】:
我正在修改 Intermediate Perl 中介绍的 Moose。我有一个抽象类Animal,其属性为sound。默认行为应该是抱怨 sound 必须在子类中定义:
package Animal;
use namespace::autoclean;
use Moose;
has 'sound' => (
is => 'ro',
default => sub {
confess shift, " needs to define sound!"
}
);
1;
子类除了定义sound之外什么都不做:
package Horse;
use namespace::autoclean;
use Moose;
extends 'Animal';
sub sound { 'neigh' }
1;
但是用
进行测试use strict;
use warnings;
use 5.010;
use Horse;
my $talking = Horse->new;
say "The horse says ", $talking->sound, '.';
结果
Horse=HASH(0x3029d30) needs to define sound!
如果我用更简单的东西替换 Animal 中的匿名函数
has 'sound' => (
is => 'ro',
default => 'something generic',
);
一切正常。这是为什么?为什么我在子类中重写了默认函数?
【问题讨论】: