Perl,Moose - 子类不是继承超类的方法

时间:2013-10-15 19:06:32

标签: perl oop inheritance moose

我是Perl的新手,并被指示为Moose作为Perl OO的来源,但我在使其工作方面遇到了一些问题。具体来说,超类的方法似乎没有被继承。 为了测试这个,我创建了三个包含以下内容的文件:

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();

在我的再见方法中,调用再见不会产生覆盖的结果,只打印“忽略”。

2 个答案:

答案 0 :(得分:8)

你有一个函数调用,而不是方法调用。继承仅适用于类和对象,即方法调用。方法调用看起来像$object->method$class->method

sub hello
{
    my ($self) = @_;
    $self->bye();
}

顺便说一下,require "thing_inherited.pm";应为use thing_inherited;

答案 1 :(得分:0)

只是一些修复。 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 $