perl - 正确的 Perl OO 继承

标签 perl oop inheritance

我正在尝试创建我们代码库中的自定义模块的子类。我们的模块位于包含在所有文件中的目录中。所以我们开始

use Env;
use lib "$ENV{OurKey}/RootLib"; # All of our modules are here

接下来,我有我的父模块,位于 RootLib/Dir1/Parent.pm 中,其代码已经存在很长时间了,所以我宁愿不更改其中任何一个,而是拥有 child 能够按原样继承它。

package Parent;
use strict;
use warnings;
use Env;
use lib "$ENV{OurKey}/RootLib";

sub new {
    my $proto = shift;
    my $class = ref($proto) || $proto;
    my $self = {};

    # Some other stuff

    bless ($self, $class);
    return $self;
}

此时,我有点迷失,因为我已经看到了许多不同的方法来定义子构造函数,但没有一个对我有用。这就是我所拥有的,但它不起作用,因为在子包中找不到应该从父包继承的子例程。子包位于 RootLib/Dir1/Dir2/Child.pm

package Child;
use strict;
use warnings;
use vars qw(@ISA);
use Env;
use lib "$ENV{OurKey}/RootLib";

require Dir1::Parent;
push @ISA, 'Dir1::Parent';

sub new {
    # This constructor is clearly incorrect, please help
    my $proto = shift;
    my $class = ref($proto) || $proto;
    my $self = Parent::new($class);

    bless ($self, $class);
    return $self;
}

然后,在我的 test.pl 文件中,我有

use Env;
use lib "$ENV{OurKey}/RootLib";
use Dir1::Dir2::Child;

my $childObj = Child->new();
$childObj->inheritedParentSubroutine( ... ); # Cannot find this subroutine

最佳答案

父类声明它位于Parent包中(即使包含它的文件是Dir1/Parent.pm),因此子类的@ISA 应该只包含 Parent

或者您可以使用一些额外的 use lib ... 语句来解决不幸的目录结构。

package Child;
use lib "$ENV{OurKey}/RootLib/Dir1";
require Parent;      # found in $OurKey/RootLib/Dir1/Parent.pm
our @ISA = ('Parent');
...

# test.pl
use lib "$ENV{OurKey}/RootLib/Dir1/Dir2";
use Child;           # found in $OurKey/RootLib/Dir1/Dir2/Child.pm
...

关于perl - 正确的 Perl OO 继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32978483/

相关文章:

c# - 为什么.NET Framework 4.0 中的静态类Tuple 可以有new 关键字来创建实例?

java - 如何在不使用instanceOf或getClass()的情况下知道类类型?

python - 我正在寻找什么样的设计模式以及如何在 python 中实现它

php - 从子方法访问时,父方法设置的父类属性为空

c++ - 继承中的基类是否复制到派生类中?

python - 关于继承Python的方法重写

json - 使用 Perl 编码复杂的 JSON 结构

linux - 如何处理ssh key ?

java - 这个正则表达式有什么作用?

arrays - perl丢弃映射操作中的第一个数组元素