實(shí)例解析Perl繼承用法
本文和大家重點(diǎn)討論一下Perl繼承的概念和用法,繼承簡(jiǎn)單的說(shuō)就是一個(gè)類(lèi)繼承另一個(gè)類(lèi)后,可以使用被繼承類(lèi)的方法。希望本文的介紹能讓你有所收獲。
Perl繼承
類(lèi)方法通過(guò)@ISA數(shù)組Perl繼承,變量的Perl繼承必須明確設(shè)定。下例創(chuàng)建兩個(gè)類(lèi)Bean.pm和Coffee.pm,其中Coffee.pmPerl繼承Bean.pm的一些功能。此例演示如何從基類(lèi)(或稱(chēng)超類(lèi))Perl繼承實(shí)例變量,其方法為調(diào)用基類(lèi)的構(gòu)造函數(shù)并把自己的實(shí)例變量加到新對(duì)象中。
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;
此類(lèi)中,用$this變量設(shè)置一個(gè)匿名哈希表,將'Bean'類(lèi)型設(shè)為'Colombian'。方法setBeanType()用于改變'Bean'類(lèi)型,它使用$class引用獲得對(duì)對(duì)象哈希表的訪(fǎng)問(wèn)。
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;語(yǔ)句包含了Bean.pm文件和所有相關(guān)函數(shù),方法setCoffeeType()用于設(shè)置局域變量$class->{'Coffee'}的值。在構(gòu)造函數(shù)new()中,$this指向Bean.pm返回的匿名哈希表的指針,而不是在本地創(chuàng)建一個(gè),下面兩個(gè)語(yǔ)句分別為創(chuàng)建不同的哈希表從而與Bean.pm構(gòu)造函數(shù)創(chuàng)建的哈希表無(wú)關(guān)的情況和Perl繼承的情況:
my$this={};#非Perl繼承
my$this=$theSuperClass->new();#Perl繼承
下面代碼演示如何調(diào)用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";
該代碼的結(jié)果輸出如下:
- --------------------Initialvalues------------
- Coffee:Instant
- Bean:Colombian
- --------------------ChangeBeanType----------
- SetbeantoMixed
- BeanTypeisnowMixed
- ------------------ChangeCoffeeType----------
- SetcoffeetypetoInstant
- Typeofcoffee:Instant
上述代碼中,先輸出對(duì)象創(chuàng)建時(shí)哈希表中索引為'Bean'和'Coffee'的值,然后調(diào)用各成員函數(shù)改變值后再輸出。
【編輯推薦】
- 構(gòu)造函數(shù)中Perl方法用法解析
- Perl文件句柄概念詳解
- 解析四大Perl操作符用法
- 淺析Perl面向?qū)ο缶幊逃梅?/a>
- Perl標(biāo)量轉(zhuǎn)換函數(shù)用法指南