在 Perl 中扩展 Class::Accessor 以在父 class 中设置一些属性
Extending a Class::Accessor in Perl to set some properties in parent class
我有一个 Class 定义为 Class::Accessor 像这样:
package Worker;
use Class::Accessor 'antlers';
# PROPS
has first_name => ( is => 'rw' );
has position => ( is => 'rw' );
# METHODS
sub print {
my $self = shift;
print "------------\n";
print "Ref: ", ref $self, "\n";
print "First Name: ", $self->first_name, "\n";
if ($self->position) {
print "Position: ", $self->position, "\n";
}
}
1;
现在我想创建工程师 class 以 属性 始终设置为这样的方式扩展 Worker:position => 'Engineer'
例如:
package Engineer;
use Class::Accessor 'antlers';
use Worker;
extends(qw/Worker/);
# METHOS
sub new {
return bless(__PACKAGE__->SUPER::new({position => 'Engineer'}));
}
1;
但这不起作用,因为当我像这样实例化工程师 class 时:
use Data::Dumper;
use strict;
# Relative Path to Class libraries
use FindBin;
use lib "$FindBin::Bin/.";
use Worker;
use Engineer;
my $wor = Worker->new({first_name => 'Matt'});
my $eng = Engineer->new({first_name => 'Ray'});
$wor->print;
$eng->print;
我在扩展 class 中松开 first_name 工程师:
------------
Ref: Worker
First Name: Matt
------------
Ref: Engineer
First Name:
Position: Engineer
另一方面,我不确定覆盖 Engineer->new() 方法返回祝福是否是个好主意...
那么,我应该如何使用 Class::Accessor 扩展工人 class 以获得工程师 class?
这个新的覆盖似乎运行良好:
package Engineer;
use Class::Accessor 'antlers';
use Worker;
use Data::Dumper;
extends(qw/Worker/);
# METHODS
sub new {
my($class) = shift;
my $obj = __PACKAGE__->SUPER::new(@_);
$obj->position('engineer');
return bless $obj, $class;
}
Setter 和 getter 仍然适用于所有字段,'position' 字段在实例化对象时初始化。
我有一个 Class 定义为 Class::Accessor 像这样:
package Worker;
use Class::Accessor 'antlers';
# PROPS
has first_name => ( is => 'rw' );
has position => ( is => 'rw' );
# METHODS
sub print {
my $self = shift;
print "------------\n";
print "Ref: ", ref $self, "\n";
print "First Name: ", $self->first_name, "\n";
if ($self->position) {
print "Position: ", $self->position, "\n";
}
}
1;
现在我想创建工程师 class 以 属性 始终设置为这样的方式扩展 Worker:position => 'Engineer'
例如:
package Engineer;
use Class::Accessor 'antlers';
use Worker;
extends(qw/Worker/);
# METHOS
sub new {
return bless(__PACKAGE__->SUPER::new({position => 'Engineer'}));
}
1;
但这不起作用,因为当我像这样实例化工程师 class 时:
use Data::Dumper;
use strict;
# Relative Path to Class libraries
use FindBin;
use lib "$FindBin::Bin/.";
use Worker;
use Engineer;
my $wor = Worker->new({first_name => 'Matt'});
my $eng = Engineer->new({first_name => 'Ray'});
$wor->print;
$eng->print;
我在扩展 class 中松开 first_name 工程师:
------------
Ref: Worker
First Name: Matt
------------
Ref: Engineer
First Name:
Position: Engineer
另一方面,我不确定覆盖 Engineer->new() 方法返回祝福是否是个好主意...
那么,我应该如何使用 Class::Accessor 扩展工人 class 以获得工程师 class?
这个新的覆盖似乎运行良好:
package Engineer;
use Class::Accessor 'antlers';
use Worker;
use Data::Dumper;
extends(qw/Worker/);
# METHODS
sub new {
my($class) = shift;
my $obj = __PACKAGE__->SUPER::new(@_);
$obj->position('engineer');
return bless $obj, $class;
}
Setter 和 getter 仍然适用于所有字段,'position' 字段在实例化对象时初始化。