Perl,Moose - 子类不是继承超类的方法
问题描述:
我是Perl新手,被定向到Moose作为Perl OO的源代码,但是我在使它工作时遇到了一些问题。具体而言,超类的方法似乎不被继承。 为了测试这一点,我已经创建了包含以下三个文件:Perl,Moose - 子类不是继承超类的方法
thingtest.pl
use strict;
use warnings;
require "thing_inherited.pm";
thing_inherited->hello();
thing.pm
package thing;
use strict;
use warnings;
use Moose;
sub hello
{
print "poo";
}
sub bye
{
print "naaaa";
}
1;
最后,thing_inherited.pm
package thing_inherited;
use strict;
use warnings;
use Moose;
extends "thing";
sub hello
{
bye();
}
1;
那么人们通常会期望的是方法再见被继承作为子类,但我给这个错误,而不是...
Undefined subroutine &thing_inherited::bye called at thing_inherited.pm line 11.
任何人都可以解释,如果我在这里做错了什么?谢谢!
编辑:在这样做的过程中,我遇到了另一个难题:从我的超类中调用基本类中的方法应该已被超类覆盖。 说我在我的基类有
sub whatever
{
print "ignored";
}
,并在我再见方法添加
whatever();
,要求再见不会产生被覆盖的结果,仅打印“忽略不计”。
答
你有一个函数调用,而不是方法调用。继承只适用于类和对象,即方法调用。方法调用看起来像$object->method
或$class->method
。
sub hello
{
my ($self) = @_;
$self->bye();
}
顺便说一句,require "thing_inherited.pm";
应该是use thing_inherited;
答
只是一些修正。 thing.pm很好,但看到thingtest.pl和thing_inherited.pm的更改。
thingtest.pl:使用前需要先实例化对象,那么你可以使用的方法
use thing_inherited;
use strict;
use warnings;
my $thing = thing_inherited->new();
$thing->hello();
thing_inherited.pm:因为hello方法是调用它的类中的方法,你需要告诉它只是
package thing_inherited;
use strict;
use warnings;
use Moose;
extends "thing";
sub hello {
my $self = shift;
$self->bye();
}
1;
输出:
$ perl的thingtest.pl
naaaa $
(在参观SO的姊妹网站之一,我得到了我得到了“驼鹿徽章”的通知。没有上下文,我认为“什么,为了成为加拿大人?”) – ikegami