通过ISA实现Perl继承
关于使用@ISA在Perl中进行继承的问题: 输入-3个文件:一个是主脚本,两个包含父和子包,相应地: 主要内容: 下午三时通过ISA实现Perl继承,perl,inheritance,packages,Perl,Inheritance,Packages,关于使用@ISA在Perl中进行继承的问题: 输入-3个文件:一个是主脚本,两个包含父和子包,相应地: 主要内容: 下午三时 package parent; sub srictly_parent_function { print "this is strictly parent function\n"; } sub parent_or_child_function { print "this is parent function which can be inherited\
package parent;
sub srictly_parent_function
{
print "this is strictly parent function\n";
}
sub parent_or_child_function
{
print "this is parent function which can be inherited\n";
}
1;
child.pm:
package child;
our @ISA = 'parent';
use Exporter qw(import);
@EXPORT_OK = qw(parent_or_child_function srictly_parent_function);
sub parent_or_child_function
{
print "this is child function that replaced parent's\n";
}
1;
输出为:
$main
this is child function that replaced parent's
Undefined subroutine &child::srictly_parent_function called at main line 6.
我做错了什么?我知道child包没有严格的\u parent\u函数,但是child的@ISA包不应该被搜索吗?首先,让parent实际上是一个对象
package parent;
use strict;
use warnings;
# Constructor
sub new {
my ($proto) = @_;
my $class = ref($proto) || $proto;
my $self = {};
# Bless is what casts $self (instance of this class) as an object
return bless($self, $class);
}
sub srictly_parent_function {
my ($self) = @_;
print "this is strictly parent function\n";
}
sub parent_or_child_function {
my ($self) = @_;
print "this is parent function which can be inherited\n";
}
1;
然后将父对象作为对象,子对象可以继承
package child;
use strict;
use warnings;
# I prefer use base, as it's safer than pushing classes into @ISA
# See http://docstore.mik.ua/orelly/perl2/prog/ch31_03.htm)
use base qw(parent);
sub parent_or_child_function {
my ($self) = @_;
print "this is child function that replaced parent's\n";
}
# To give an example for accessing variables from a class.
my $variable = "WHATEVER";
sub get_variable { return $variable;}
1;
然后,要测试您的代码:
perl -e "use child; $object = child->new(); $object->parent_or_child_function();"
或者适当地编写脚本
# Load up child class
use child qw();
# Invoke constructor to create an instance of the class
my $object = child->new();
# Invoke function from child class
$object->parent_or_child_function();
# Get Variable
$object->get_variable();
关于“我做错了什么?”,1)继承是对象的一个特性,但您没有对象。2) 您导出了
&child::srictly\u parent\u函数
,但从未定义过它。谢谢。这解释得相当全面。不过,这又引出了另一个问题——如果我在包中声明了一个变量怎么办?我可以通过类(包)对象访问这个变量吗?抱歉,刚刚从4天的假期返回。您始终可以访问类中的任何变量。只需为它编写一个公共访问器,它将返回该变量。(参见修改后的示例)
# Load up child class
use child qw();
# Invoke constructor to create an instance of the class
my $object = child->new();
# Invoke function from child class
$object->parent_or_child_function();
# Get Variable
$object->get_variable();