我有两个类,一个是基类(Employee),另一个是继承它的子类(扩展),其代码如下所示:
package Employee;
require Exporter;
our @EXPORT = ("getattr");
our $private = "This is a class level variable";
sub getattr {
print "Inside the getattr function of Employee.pm module \n";
$self = shift;
$attr = shift;
return ($self->{$attr});
}
1;
================
package Extend;
use base qw(Employee);
sub new {
print "Inside new method of Employee.pm \n";
my $class = shift;
my %data = (
name => shift,
age => shift,
);
bless \%data , $class;
}
sub test {
print "Inside test method of Extend class \n";
}
1;
==================
现在我有另一段使用 Extend 类的代码:
use Extend;
my $obj = Extend->new("Subhayan",30);
my $value = $obj->getattr("age");
print ("The value of variable age is : $value \n");
$obj->test();
print "Do i get this : $obj.$private \n";
我的问题是关于父类中定义的变量 $private 。根据我的继承概念,父类的属性和方法应该通过子类对象可用。例如函数 getattr 运行良好。但为什么我无法使用基类 Extend 对象访问 $private 变量。
我在这里缺少什么?有人可以帮忙吗?
最佳答案
变量的继承方式与子变量不同。要访问它,您需要指定整个包名称(是的,当您声明 $private
时,您需要 our
,而不是 my
) :
print "$Employee::private\n";
定义访问器方法更加健壮:
# Employee package
sub private {
return $private;
}
...然后在您的脚本中:
my $var = private();
要从 Employee 继承对象属性,您可以执行以下操作:
# Employee
sub new {
my $self = bless {
dept => 'HR',
hours => '9-5',
}, shift;
return $self;
}
# Extend
sub new {
my $class = shift;
my $self = $class->SUPER::new; # attrs inherited from Employee
$self->{extended} = 1;
return $self;
}
# script
my $extend = Extend->new;
现在 $extend
看起来像:
{
dept => 'HR',
hours => '9-5',
extended => 1,
}
您很可能不会在基类中设置部门或时间,因为它将适用于所有员工,但我离题了。
关于perl - Perl 中的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37364935/