本文和大家重点讨论一下Perl继承的概念和用法,继承简单的说就是一个类继承另一个类后,可以使用被继承类的方法。希望本文的介绍能让你有所收获。

目前创新互联已为近1000家的企业提供了网站建设、域名、虚拟主机、网站改版维护、企业网站设计、平乐网站维护等服务,公司将坚持客户导向、应用为本的策略,正道将秉承"和谐、参与、激情"的文化,与客户和合作伙伴齐心协力一起成长,共同发展。
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";
 
该代码的结果输出如下:
- --------------------Initialvalues------------
 - Coffee:Instant
 - Bean:Colombian
 - --------------------ChangeBeanType----------
 - SetbeantoMixed
 - BeanTypeisnowMixed
 - ------------------ChangeCoffeeType----------
 - SetcoffeetypetoInstant
 - Typeofcoffee:Instant
 
上述代码中,先输出对象创建时哈希表中索引为'Bean'和'Coffee'的值,然后调用各成员函数改变值后再输出。
                分享标题:实例解析Perl继承用法
                
                转载注明:http://www.csdahua.cn/qtweb/news47/493597.html
            
网站建设、网络推广公司-快上网,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 快上网