实例解析Perl继承用法
本文和大家重点讨论一下Perl继承的概念和用法,继承简单的说就是一个类继承另一个类后,可以使用被继承类的方法。希望本文的介绍能让你有所收获。
Perl继承
类方法通过@ISA数组Perl继承,变量的Perl继承必须明确设定。下例创建两个类Bean.pm和Coffee.pm,其中Coffee.pmPerl继承Bean.pm的一些功能。此例演示如何从基类(或称超类)Perl继承实例变量,其方法为调用基类的构造函数并把自己的实例变量加到新对象中。
Bean.pm代码如下:
packageBean;
requireExporter;
@ISA=qw(Exporter);
@EXPORT=qw(setBeanType);
subnew{
my$type=shift;
my$this={};
$this->{'Bean'}='Colombian';
bless$this,$type;
return$this;
}
#
#Thissubroutinesetstheclassname
subsetBeanType{
my($class,$name)=@_;
$class->{'Bean'}=$name;
print"Setbeanto$name\n";
}
1; 此类中,用$this变量设置一个匿名哈希表,将'Bean'类型设为'Colombian'。方法setBeanType()用于改变'Bean'类型,它使用$class引用获得对对象哈希表的访问。
Coffee.pm代码如下:
1#
2#TheCoffee.pmfiletoillustrateinheritance.
3#
4packageCoffee;
5requireExporter;
6requireBean;
7@ISA=qw(Exporter,Bean);
8@EXPORT=qw(setImports,declareMain,closeMain);
9#
10#setitem
11#
12subsetCoffeeType{
13my($class,$name)=@_;
14$class->{'Coffee'}=$name;
15print"Setcoffeetypeto$name\n";
16}
17#
18#constructor
19#
20subnew{
21my$type=shift;
22my$this=Bean->new();#####<-LOOKHERE!!!####
23$this->{'Coffee'}='Instant';#unlesstoldotherwise
24bless$this,$type;
25return$this;
26}
271; 第6行的requireBean;语句包含了Bean.pm文件和所有相关函数,方法setCoffeeType()用于设置局域变量$class->{'Coffee'}的值。在构造函数new()中,$this指向Bean.pm返回的匿名哈希表的指针,而不是在本地创建一个,下面两个语句分别为创建不同的哈希表从而与Bean.pm构造函数创建的哈希表无关的情况和Perl继承的情况:
my$this={};#非Perl继承
my$this=$theSuperClass->new();#Perl继承
下面代码演示如何调用Perl继承的方法:
1#!/usr/bin/perl
2push(@INC,'pwd');
3useCoffee;
4$cup=newCoffee;
5print"\n--------------------Initialvalues------------\n";
6print"Coffee:$cup->{'Coffee'}\n";
7print"Bean:$cup->{'Bean'}\n";
8print"\n--------------------ChangeBeanType----------\n";
9$cup->setBeanType('Mixed');
10print"BeanTypeisnow$cup->{'Bean'}\n";
11print"\n------------------ChangeCoffeeType----------\n";
12$cup->setCoffeeType('Instant');
13print"Typeofcoffee:$cup->{'Coffee'}\n"; 该代码的结果输出如下:
相关推荐
边城客栈学无止境 2020-07-05
Walter的学习笔记 2020-07-04
A宇 2020-06-14
边城客栈学无止境 2020-06-10
邓博学习笔记 2020-06-03
davidliu00 2020-05-26
ShiShuo 2020-05-16
Aggressivesnail 2020-05-10
ShiShuo 2020-04-26
hanxingwang00 2020-04-22
davidliu00 2020-03-06
ShiShuo 2020-03-06
ShiShuo 2020-03-05
Aggressivesnail 2020-02-28
aaLiweipeng 2020-02-01
amberom 2020-01-16
Walter的学习笔记 2020-01-06