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