Perl是否可以在不实现构造函数的情况下创建子类?我不需要任何特定于子类的构造函数行为,所以我想从父类继承。
在这个例子中,我有一个基类Base.pm
和一个子类Child.pm
。 Child
类应该简单地覆盖其父方法之一:
# test.pl
use strict;
use warnings;
use Child;
my $o = Child->new();
$o->exec();
-
# Base.pm
package Base;
sub new{
my $self = {};
bless $self;
return $self;
}
sub exec{
my $self = shift;
die "I'm in the Base class\n";
}
1;
-
# Child.pm
package Child;
use Base;
@ISA = ('Base');
sub exec{
my $self = shift;
die "OVERRIDE in child\n";
}
1;
当我运行test.pl时, Base类的 exec方法被执行(我假设它是因为该对象在Base
构造函数中被祝福为Base.pm
)。
$ ./test.pl
I'm the Base class
有没有办法实现子类而不必重新实现构造函数?
答案 0 :(得分:7)
是
您实际拥有以下内容:
sub new {
return bless({});
}
将其替换为以下内容:
sub new {
my $class = shift;
return bless({}, $class);
}
基本上,始终使用bless
的双参数形式。
我如何编写构造函数:
基类:
sub new {
my ($class, ...) = @_;
my $self = bless({}, $class);
$self->{...} = ...;
return $self;
}
派生类:
sub new {
my ($class, ...) = @_;
my $self = $class->SUPER::new(...);
$self->{...} = ...;
return $self;
}
我喜欢对称性。