【问题标题】:Perl, Moose - subclass is not inheriting methods of a superclassPerl,Moose - 子类不继承超类的方法
【发布时间】:2013-10-23 17:20:33
【问题描述】:

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

thingtest.pl

use strict;
use warnings;
require "thing_inherited.pm";
thing_inherited->hello();

东西.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;

所以人们通常期望方法 bye 作为子类的一部分被继承,但我却得到了这个错误......

Undefined subroutine &thing_inherited::bye called at thing_inherited.pm line 11.

如果我在这里做错了什么,谁能解释一下?谢谢!

edit:在这样做时,我遇到了另一个难题:从我的超类调用我的基类中应该被超类覆盖的方法没有被覆盖。 说我有

sub whatever
{

    print "ignored";

}

在我的基类中并添加了

whatever();

在我的 bye 方法中,调用 bye 不会产生被覆盖的结果,只会打印“ignored”。

【问题讨论】:

    标签: perl oop inheritance moose


    【解决方案1】:

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

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

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

    【讨论】:

    • (在访问 SO 的一个姊妹网站时,我收到通知我得到了“驼鹿徽章”。没有上下文,我想“什么,因为是加拿大人???”)
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 2019-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-04
      相关资源
      最近更新 更多