Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Perl中扩展Class::Accessor以设置父类中的某些属性_Perl_Accessor - Fatal编程技术网

在Perl中扩展Class::Accessor以设置父类中的某些属性

在Perl中扩展Class::Accessor以设置父类中的某些属性,perl,accessor,Perl,Accessor,我有一个用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 "-----------

我有一个用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;
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;
现在我想创建一个Engineer类,它以这样一种方式扩展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;
但这不起作用,因为当我像这样实例化Engineer类时:

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;
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;
我失去了扩展类工程师的第一个名字:

------------
Ref: Worker
First Name: Matt
------------
Ref: Engineer
First Name: 
Position: Engineer
另一方面,我不确定重写返回bless的Engineer->new()方法是否是个好主意


那么,我应该如何使用class::Accessor扩展Worker类以获得工程师类呢?

这个新的覆盖似乎工作得很好:

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”字段