perl - Perl 中的继承

标签 perl

我有两个类,一个是基类(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/

相关文章:

string - 在 Perl 中,如何生成由八个十六进制数字组成的随机字符串?

perl - 如何在 Perl 中不活跃

mysql - 如何将带引号的字符串插入到 Perl DBI 查询中?

perl - 有没有办法让 screen 返回 session id 或 pid?

xml - LWP::UserAgent 将 XML 发布到安全服务器...证书问题

regex - 无法识别的转义\R 在 test.pl 第 7 行通过

multithreading - 线程::队列什么都不返回

perl - 在标量上下文中使用时,我可以控制 Moose 对象的值吗?

perl - 如何有条件地使警告致命?

RegEx 和 Mod_rewrite 将动态 URL 转换为静态 URL,将静态 URL 转换为动态 URL